[英]Wordpress category loop, how to hide cats with no posts?
I found this code at this web site 我在此网站上找到了此代码
But it prints the cat name (the ) even if there's no posts under that category. 但是,即使该类别下没有帖子,它也会打印出猫的名字()。 How would I modify this code to NOT print the header in there are no posts in the cat?
我将如何修改此代码,以免在cat中没有帖子的情况下不打印标题?
<?php
// get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= $cat->term_id;
// Make a header for the cateogry
echo "<h2>".$cat->name."</h2>";
// create a custom wordpress query
query_posts("cat=$cat_id&tag=torrington&post_per_page=100");
// start the wordpress loop!
if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php // create our link now that the post is setup ?>
<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
<?php echo '<hr/>'; ?>
<?php endwhile; endif; // done our wordpress loop. Will start again for each category ?>
<?php } // done the foreach statement ?>
Make this line: 进行以下一行:
echo "<h2>".$cat->name."</h2>";
only execute if have_posts()
is true. 仅在
have_posts()
为true时执行。
<?php
// get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= $cat->term_id;
// create a custom wordpress query
query_posts("cat=$cat_id&tag=torrington&post_per_page=100");
// start the wordpress loop!
if (have_posts()):
// Make a header for the cateogry
echo "<h2>".$cat->name."</h2>";
while (have_posts()):
the_post();
// create our link now that the post is setup
?>
<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
<?php echo '<hr/>';
endwhile;
endif; // done our wordpress loop. Will start again for each category
} // done the foreach statement
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.