Wordpress:显示所有类别,但如果一个类别只包含一个 post,则显示此 post

Wordpresss: display all categories, but if one contains only one post, display this post instead

我还是 WordPress 的新手(PHP),我正在尝试完成我的第一个模板。 当前请求是显示所有给定的(子)类别,但如果一个类别只有一个 post,它应该显示 post 而不是摘录。我想我只缺少一小部分来完成这个...

我目前拥有的:

<?php 
     if(!empty($categories)) { ?>
               
         <!-- Display Sub-Categories and description -->
         <div class="brick_list">
            <?php                   
                 foreach ( $categories as $category ) {
                     echo '<div class="item"><h4 class="item-title">' . $category->name . '</h4><div class="item-text">' . $category->description . '</div><div class="item-link"><a href="' . get_category_link( $category->term_id ) . '">Read more</a></div></div>';
                 }
             ?>
         </div>

<?php }; ?>

我在网上搜索了“类别中只有一个 post”任务的解决方案,发现了这个:

if( 1 == $category[0]->count ) { ..... }

但我不知道如何将它包含(或合并)到我现有的 foreach 循环中。 有人可以帮忙吗?

我稍微编辑了你的代码,我添加了一个条件来在显示 div 元素之前检查类别计数。

<?php

$categories = get_categories();

if(!empty($categories)) { ?>
               
         <!-- Display Sub-Categories and description -->
         <div class="brick_list">
            <?php                   
                 foreach ( $categories as $category ) {
                     if ( $category->count!= 1 ){
                     echo '<div class="item"><h4 class="item-title">' . $category->name . '</h4><div class="item-text">' . $category->description . '</div><div class="item-link"><a href="' . get_category_link( $category->term_id ) . '">Read more</a></div></div>';
                 } else {
                     // display the post with excerpt
                     }
                 }
                         
            
             ?>
         </div>

<?php }; ?>

?>

如果您有任何问题,请告诉我。

我能够解决它。最后看起来并不那么困难:-D 我在这里分享以防其他人需要它

<?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><div class="item-text">' . wp_trim_words( get_the_content($all_posts[0]->ID), 30, '...') . '"</div></div>';
         
         // otherwise display subcategories
         } else {
            echo '<div class="item"><h4 class="item-title">' . $category->name . '</h4><div class="item-text">' . wp_trim_words($category->description, 30, '...') . '</div></div>';
         }
    }
?>