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 of this 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?
PS: yes, I am an absolute WP beginner.... :-(
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 of this 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?
PS: yes, I am an absolute WP beginner.... :-(
Share Improve this question asked Aug 14, 2020 at 13:36 JonSnowJonSnow 1156 bronze badges1 Answer
Reset to default 0I 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>';
}
}
?>