WordPress 分类页调用置顶文章时,如果没有置顶文章会自动调用普通文章的解决办法

最近发现 WordPress 分类页调用置顶文章时,如果没有置顶文章会自动调用普通文章,我调用置顶文章的代码如下:

<?php 
	$sticky_posts = get_option( 'sticky_posts' );
	$args = array( 
	'cat'=> $cat,
	'post__in' => $sticky_posts,
	'posts_per_page' => 2,
	); 
	$query = new WP_Query( $args ); 
	while ( $query->have_posts() ) : $query->the_post();
?> 
...
<?php endwhile; wp_reset_query();?>

经过 echo 大法,发现当没有置顶文章时,post__in 这个条件就自动被忽略了,因此临时想了个解决办法,就是判断 $sticky_posts 为空时,给数组加上个 0 ,这样 post__in 就会生成一个查询 id in (0),也就查询不到了。

<?php 
	$sticky_posts = get_option( 'sticky_posts' );
 if(empty($sticky_posts)){ $sticky_posts = [0]; }
	$args = array( 
	'cat'=> $cat,
	'post__in' => $sticky_posts,
	'posts_per_page' => 2,
	); 
	$query = new WP_Query( $args ); 
	while ( $query->have_posts() ) : $query->the_post();
?> 
...
<?php endwhile; wp_reset_query();?>
WordPress 分类页调用置顶文章时,如果没有置顶文章会自动调用普通文章的解决办法

相关文章:

你感兴趣的文章:

标签云: