簡體   English   中英

類別中計數帖子的 php 循環錯誤

[英]php loop error for count posts in category

我的 wordpress 頁面上有多個類別,每個類別都有 1 到 n 個子類別。 如果一個子類別僅包含 1 個帖子,我希望顯示此帖子的摘錄,否則我將顯示該類別的描述。

我已經有了“正常”類別的部分,但是關於“單個帖子類別”有一個愚蠢的錯誤。 這是我到目前為止所擁有的:

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

結果是:我得到了正常的類別(很好。)但是多次“單個帖子類別”中的第一個,我的循環可能有問題。 但我沒看到? 有人看到錯誤了嗎?

有兩個可能的錯誤:

  1. 該類別在數組中出現了兩次(請嘗試對其進行var_dump 。)-> 可使用array_unique修復
  2. 您忘記了一些調試的回聲(某處 - 第一個解決方案應該可以解決問題。)
  3. 如果第一個解決方案沒有解決它,請發布類別數組的var_dump

我現在有一個可行的解決方案......終於!

<?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>';
         }
     }
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM