2012-11-25 158 views
0

我發現這個代碼at this web siteWordPress的類別循環,如何隱藏沒有帖子的貓?

但它打印的貓的名字(),即使沒有在該類別下的職位。如何修改此代碼以便在貓中沒有帖子的情況下打印標題?

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

回答

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 
+0

我試過了,但是會引發服務器錯誤。編輯:大部分是剪切和粘貼,我讓它工作。謝謝! – Steve

+0

*必須是 – Steve

相關問題