1

I have several posts that share the same layout but have different title and content.

This layout is different from that on the site.

I can use single.php to render them, but then ALL posts will have this layout.

If I add some category for this posts, could I render all post in this category in the same way?

I tried using category-{category-name}.php but it just rendered the page for this category.

3

I believe you are talking about single post pages. The template hierarchy does not make provision for single templates according to the category a post belongs to, so single-{$category}.php does not exist.

To make single-{$category}.php work, we can make use of the single_template filter

add_filter( 'single_template', function ( $template )
{
    global $post;
    // Check if our post has our specific category
    if ( !has_category( 1, $post ) ) // Change to your specific category
        return $template;

    // Locate and load our single-{$category}.php template
    $locate_template = locate_template( 'single-my_category.php' ); // Change to your exact template name
    if ( !$locate_template ) 
        return $template;

    // single-my_category.php exists, load it
    return $locate_template;
});

You can now just create our own custom single template and use it for any single post that belongs to the specific category you need to target

|improve this answer|||||
  • 1
    It just works!!! – Boykodev Dec 17 '15 at 10:01
1

The category templates are just for post archives listing you would need to do this within the single.php template.

You can use has_category()within the single.php template to detect if the post has the category. Then just include different files. eg:

if ( has_category( $category, $post ) ) {
    include "template-one.php";
} else {
    include "template-two.php";
}

Ref: https://codex.wordpress.org/Function_Reference/has_category

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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