在WordPress中,have_posts()
函数用于检查是否有文章匹配当前查询条件。可以极大的精简代码,提高开发效率,比如下面的代码,按照WordPress后台设置调用最新文章,并且使用指定模板来显示这些文章。
<?php while(have_posts()){ the_post(); ?>
<?php get_template_part('sections/content','dataGrid'); ?>
<?php } ?>
但是很多时候,我们可能有一些特定需求,需要自定义一些参数,而不是简单的使用默认调用。如果你想要修改 have_posts()
函数的查询条件,你可以使用 WP_Query
类来设置你自己的查询参数,然后传递这些参数给 have_posts()
函数。
一上面的代码为例,我们想要在最新文章中排除置顶文章,那么可以像下面代码这样修改 have_posts()
函数的查询条件:
<?php
$args = array(
'ignore_sticky_posts' => 1 //排除置顶文章
);
$the_query = new WP_Query( $args );
while($the_query->have_posts()){ $the_query->the_post();
?>
<?php get_template_part('sections/content','dataGrid'); ?>
<?php } wp_reset_postdata(); ?>
在这个例子中,我们创建了一个新的 WP_Query
对象,并设置了我们想要的查询参数。然后,我们使用这个自定义的查询对象来代替默认的查询,通过 have_posts()
函数输出文章。最后,我们调用了 wp_reset_postdata()
函数来清除查询,以防止影响后续的查询。
发表评论