WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] if post count = 1, use template single.php (7 posts)

  1. mikedev
    Member
    Posted 6 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?

  2. Austin Matzko
    Member
    Posted 6 years ago #

    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;
    }
  3. mikedev
    Member
    Posted 6 years ago #

    Wow, many, many thanks. This works like magic! You're awsome.

    Did you write this, or is it a standard WP function?

  4. Stefanie
    Member
    Posted 6 years ago #

    This is great. Is there a way to make it work with tag and search pages, also?

  5. Stefanie
    Member
    Posted 6 years ago #

    Nevermind, I got it!

  6. daweeed
    Member
    Posted 5 years ago #

    Thanks a lot for this hack, it made my day.

  7. GeoffCJ
    Member
    Posted 5 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

Topic Closed

This topic has been closed to new replies.

About this Topic