1

How can I make a single post display different from the other single posts when I add it to a specific category.

example: I have a post that is in 3 categories: music, songs & video clips. I want every time that I add a post in category "songs", it will be displayed differently from all of the other default single posts that don't belong to the category songs. How can I do that? Also, can the same thing happen with tags too? Meaning, when I add to a post some specific tags can it change the template of the post?

2
  • when viewed as single. I have uprated the posts were my issues and questions were answered. What else more should I do?
    – Alex
    Commented Mar 30, 2012 at 8:25
  • i think you should really look at @milo answer... he check if the post is in a specific category the gives loads a different template / design for your post... You can also paste the single.php loop and the name of the category you want things to look different in pastebin and we could help you a little bit more - bit milo got a gr8 answer
    – Sagive
    Commented Mar 30, 2012 at 16:10

1 Answer 1

1

With CSS: If your theme uses post_class() on a containing element, you can target that element with the class .category-songs to control styling.

With a template filter: add a filter to single_template and check the assigned categories for your songs category, and use the template songs-single.php if that category is found:

function wpse_check_single_categories( $template = '' ){
    $categories = get_the_category();
    foreach( $categories as $cat ):
        if( $cat->name == 'songs' ):
            $template = locate_template( array( "songs-single.php", $template ), false );
        endif;
    endforeach;
    return $template;
}
add_filter( 'single_template', 'wpse_check_single_categories' );
4
  • To understand better, where do I have to write this function? In the beginning of songs-single.php or somewhere else?
    – Alex
    Commented Apr 2, 2012 at 19:36
  • 1
    @Alex the filter code would go in your theme's functions.php file.
    – Milo
    Commented Apr 2, 2012 at 22:44
  • If I want this template to be shown to more than 1 categories what do I have to do? Also, can the same thing happen with tags too? Meaning, when I add to a post some specific tags can it change the template of the post?
    – Alex
    Commented Apr 22, 2012 at 13:47
  • @milo How would this work on the home page archives to style each post excerpt differently based on category? Commented Jan 8, 2022 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.