How to create a second single.php for posts with specific category?

I have a website where I have posts categorized with “project” and posts categorized with “blog”. Right now I’m running a loop on the frontpage where I query the “project” posts. Now I am currently creating a page where I only query the “blog” posts. The problem is, once I click on one of those “blog” posts, it pulls content from the same single.php file that my “project” posts do.

**How can I create a second single.php file where I can define what the inside of posts will look like that have the “blog” category?**

3 Comments
  1. If the post type is called “blog” you can add a singe-blog.php file and it should use that template on the blog post type.

  2. There are a few different ways to do that :

    – Using a template hierarchy:
    You can create a template file specific to the “blog” category by using WordPress’s template hierarchy. WordPress checks for specific template files in the following order: single-{post-type}-{slug}.php, single-{post-type}.php, and single.php.

    You can create a file called single-blog.php, and WordPress will use that file to display single posts with the “blog” category.

    – Using a conditional statement:
    You can also use a conditional statement in your single.php file to check the post’s category and display different content based on that.

    “`
    if ( in_category( ‘blog’ ) ) {
    // Code for displaying “blog” posts
    } else {
    // Code for displaying other posts
    }
    “`
    – Using a plugin:
    Another option is to use a plugin like “Post Template” ) which allows you to assign different templates to different posts and categories. This plugin allows you to create new templates and assign them to specific posts or categories.

    Keep in mind that the first option is the best practice because it is more efficient and follows the WordPress template hierarchy.
    In any case, and as always, it’s important to backup your website before making any changes to the theme files, to avoid any issues that might happen 👍🏼

  3. Per the [WordPress template hierarchy]), the single-{category}.php format is not supported.

    So you can either extend the template resolution logic via the template_include filter, or use conditionals within single.php.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer