Wordpress类循环,如何隐藏没有帖子的猫?

时间:2012-11-25 19:53:35

标签: php wordpress

我找到了这段代码at this web site

但即使该类别下没有帖子,它也会打印猫名(the)。我如何修改此代码以不打印标题,因为猫中没有帖子?

 <?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 ?>

1 个答案:

答案 0 :(得分:0)

建立这一行:

echo "<h2>".$cat->name."</h2>";

仅在have_posts()为真时才执行。

<?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