How to show custom post template from single page?

We know that in WordPress the default post template file is single.php. Now, I have one category name “members” and want members posts to show a custom template, like content-members.php.

I can do that via custom post template plugins. but is there a way to make that without plugins?

Read More

Maybe we can do that like this:

<?php
    if ( is_category( 'members' ) ) {

         get_template_part( 'content', 'members' );

    } else {

        get_template_part( 'content', 'common' );

    }
 ?>

I tried this already, but it’s not working and I think category is not triggering here.

Related posts

2 comments

  1. You are correct, the single.php template does not have any categories associated with it. You need to first get the category for that individual post.

    Single Category

    $category = get_the_category();
    $cat_name = $category[0]->cat_name;
    if ( $cat_name == 'Members' ) {
    
         get_template_part( 'content', 'members' );
    
    } else {
    
        get_template_part( 'content', 'common' );
    
    }
    

    One thing to note here: This grabs only the first category associated with a post. If the post is in more than one category and “members” is not the first category in the list the post will not use the correct template.

    Multiple Categories

    If you want this to work with multiple categories you need to loop through them and look for the correct one.

    $categories = get_the_category();
    $cat_exists = false;
    foreach($categories as $category) {
        if( $category->name == 'Members' ) {
            $cat_exists = true;
            break;
        }
    } 
    if ( $cat_exists ) {
    
         get_template_part( 'content', 'members' );
    
    } else {
    
        get_template_part( 'content', 'common' );
    
    }
    

Comments are closed.