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?
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.
I believe you might need to use in_category() instead of is_category().
in_category() checks if the current post is in a category, is_category() checks if it’s a category archive page.
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
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.