mikedev
Member
Posted 4 years ago #
My navigation displays categories. When a visitor clicks a category the category.php template is used, showing a list of posts with their excerpts. This works fine if there is more than one post in the category. But if there is only one post, it looks silly to have one item in a list. I am looking for a way, maybe a conditional statement or a querry, that says: if post count = 1, use template single.php instead of category.php. (Would I put that statement in category.php? I'm using NavT to create my menu.) Can anyone show me how to do that?
You could accomplish this by putting the following in your theme's functions.php file:
add_action('category_template', 'use_single_for_one_category');
function use_single_for_one_category($template = '') {
global $wp_query;
if ( 1 === (int) $wp_query->post_count ) {
$template = get_single_template();
}
return $template;
}
mikedev
Member
Posted 4 years ago #
Wow, many, many thanks. This works like magic! You're awsome.
Did you write this, or is it a standard WP function?
Stefanie
Member
Posted 4 years ago #
This is great. Is there a way to make it work with tag and search pages, also?
Stefanie
Member
Posted 4 years ago #
daweeed
Member
Posted 3 years ago #
Thanks a lot for this hack, it made my day.
GeoffCJ
Member
Posted 3 years ago #
For some reason, this isn't working for me. I assume I'm supposed to rename parts of it with my template names? I tried that, but ti still doesn't work. I'm new to WordPress and PHP, so a explanation would be very much appreciated, it is exactly the functionality I'm looking for.
Geoff