Sunday, 9 July 2017

Create Custom Single Post Templates Based on Category

First you need to open a plain text editor on your computer like Notepad and paste the following code inside it:
<?php
/*
 * Template Name: Featured Article
 * Template Post Type: post, page, product
 */
 
 get_header();  ?>

You can save this file as wpb-single-post.php

After that you can login to your WordPress admin area and create or edit a post. Scroll down a little on the post edit screen, and you will notice the new Post Attributes meta box with an option to select the template.


Want to use custom single post template based on categories? For example, posts in travel category can have a different layout, than posts in photography. Here is how you can do that. First you need to add this code to your theme’s functions.php file or a site-specific plugin.

/*
* Define a constant path to our single template folder
*/
define(SINGLE_PATH, TEMPLATEPATH . '/single');

/**
* Filter the single_template with our custom function
*/
add_filter('single_template', 'my_single_template');

/**
* Single template function which will choose our template
*/
function my_single_template($single) {
global $wp_query, $post;

/**
* Checks for single template by category
* Check by category slug and ID
*/
foreach((array)get_the_category() as $cat) :

if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';

elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';

endforeach;
}
We hope this article helped you learn how to create custom single 
post templates in WordPress.You may also want to see our list of
extremely useful tricks for the WordPress functions.php file.

No comments:

Post a Comment