Sunday 9 July 2017

How To Create a Custom Post Template

Have you ever wanted to use a different template on a post? By default, most WordPress themes don’t normally offer a range of templates to choose from to use on different posts.
Pages however, are a different story and even the free Twenty Eleven default theme for WordPress offers 7 different ones to choose from.
Using the default post template on all your blog posts is a bit boring so if you want to show you subscribers a different format for a particular reason then those templates can be copied over and used to create unique posts.
Depending on the theme you have installed, yours should also offer a range of different page templates which can be used on posts as well if you follow this little trick i have for you.

Using a Plugin

Rather than playing around with php code, the easiest way to use your page templates on posts is to simply install the custom post template plugin.
Once you’ve installed the plugin by Simon Wheatley, you’ll find a module under your post tags in your Edit Post screen.
Its now time to create a post template by copying one of your existing page templates to your child themes folder.


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.