简体   繁体   中英

php loop error for count posts in category

I have multiple categories on my wordpress page and each of the categories has 1 to n subcategories. If a subcategory contains only 1 single post I would love to display an excerpt of this post, otherwise I'll display a description of the category.

I already have the part with the "normal" categories, but there is kind of a stupid mistake regarding the "single post categories". This is what I have so far:

<?php                   
  $args = array(
     'orderby' => 'slug',
     'child_of' => $cat_id,
  );

  $categories = get_categories( $args ); 


  foreach ( $categories as $category ) {
                            
      $cat_count = get_category($category->cat_ID);
        
      if($cat_count->count == 1) { ?>
           <!-- Cat has only one post, display post -->
      <?php } else {
           <!-- Cat has multiple posts, display cat description -->  
      }
  }
?>

Result is: I am getting the normal categories (fine.) but the first of the "single post categories" multiple times, Something might be wrong with my loop. but I don't see it? Does someone see the mistake?

There are two possible mistakes:

  1. The category is two times in the array (Please try to var_dump it.) -> fixable with array_unique https://www.php.net/manual/de/function.array-unique.php
  2. You forgot an echo of some debug (Somewhere - the first solution should do the trick.)
  3. If the First Solution doesn't fix it, please post the var_dump of the array of categories.

I have a working solution now... finally!

<?php                   
     foreach ( $categories as $category ) {
                                
         // If there is only one post available, go directly to the post
         if($category->count == 1) {

            $all_posts = get_posts($category);
            echo '<div class="item"><h4 class="item-title">' . get_the_title($all_posts[0]->ID) . '</h4><a href="' . get_permalink($all_posts[0]->ID) . '">Read more</a></div>';

         } else {

            echo '<div class="item"><h4 class="item-title">' . $category->name . '</h4><a href="' . get_category_link( $category->term_id ) . '">Read more</a></div>';
         }
     }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM