可以在循环之前进行条件检查,以查看查询是否有帖子。如果有帖子要显示,则只显示标题和div。
$your_query = new WP_Query( $args );
if( $your_query->have_posts() ) : // Add this line here to check if the query has posts.
echo \'<div class="posts-group">\';
echo \'<h2>More blog posts</h2>\';
while( $your_query->have_posts() ) : $your_query->the_post();
还要确保在循环结束后关闭新的IF语句:
endwhile;
echo \'</div><br>\';
endif; // Add this line to close the IF-statement.
Update:
在查询中排除当前帖子以使其生效。否则,查询仍包含当前帖子。代码如下:
$args = array(
\'post__not_in\' => array( get_the_ID() ), //Add this line to exclude the current post.
\'post_type\' => \'blog\',
\'posts_per_page\' => 5,
\'tax_query\' => array(
array(
\'taxonomy\' => \'blog-athlete\',
\'field\' => \'id\',
\'terms\' => $cat_ids
)
)
);
$relatedquery = new WP_Query( $args );
if( $relatedquery->have_posts() ) :
echo \'<div class="posts-group">\';
echo \'<h2>More blog posts:</h2>\';
while( $relatedquery->have_posts() ) : $relatedquery->the_post();
//Removed the IF here
echo \'
<article class="post home-post">
<a href="\' . get_permalink() . \'">
<div class="post-thumbnail-img">
\' . get_the_post_thumbnail($_post->ID, "small-thumbnail") . \'
</div>
<h2>\' . get_the_title() . \'</h2>
</a>
</article>\';
// Removed the closing of the IF here
endwhile;
echo \'</div><br>\';
endif;