How to display sub categories on category page if category has subcategories else show posts of that categories wordpress category page
1
votes
2 Answers
1
votes
$id = $wp_query->get_queried_object_id(); // now you have the ID of the category
Now check if something is returned and do whatever from there:
$args = array('child_of' => $id);
$subcats = get_terms( $args );
if(!empty($subcats)){
foreach($subcats as $subcat) {
echo get_term_link( $subcat->slug, $subcat->taxonomy ); // for example
}
} else {
// do the usual stuff
}
1
votes
You can try get_categories() with args child_of function like below.
$args = array('child_of' => 'category_id');
$categories = get_categories( $args );
foreach($categories as $category) {
echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
echo '<p> Description:'. $category->description . '</p>';
echo '<p> Post Count: '. $category->count . '</p>';
}
Also, $category->count ===0 then category has no post. we can use it to check that category's post.