How to create custom post template in wordpress?

In this article we will teach you how to create custom post template in wordpress.

In WordPress Template is a file which creates a layout or design of your wordpress pages. There are many types of templates in wordpress like Post Template, Page Template, Category Template, Archives Template, Author Templates. Sometimes we need a custom design for our wordpress posts or pages. And We can achieve this by create custom templates.

There are two methods to create custom post template in wordpres:

Custom Post Template With Plugin

If you want to create custom post template with plugin then you can use Post Custom Templates Lite plugin. This plugin comes with 2 ready to use templates. You can also create as many custom responsive templates as you like.

Custom Post Template Without Plugin

If you want to create custom post template without plugin then you can use the code given below.

To create custom template for post, page, product. Create a file custom-template.php and add the code given below.

<?php
/*
 * Template Name: Featured Article
 * Template Post Type: post, page, product
 */

get_header(); 

?>

<div id="primary">
	<!-- Your custom html here -->

	<?php

	while ( have_posts() ) : the_post();

	endwhile;

	?>

</div>

<?php

get_footer();

?>

In the above code you can add your own html and css to design the layout.

If you want to create custom template based on category then add the code given below in your functions.php file located at website_root_path/wp-content/themes/your_theme/functions.php . If you have category movies then create a file single-cat-movies.php.


/*
* 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_category_template');
 
/**
* Single template function which will choose our template
*/
function my_category_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';
 
endforeach;
}

That’s it now using the code above you can create custom post template in wordpress for any post type or category.

If you want more tutorials and tricks about wordpress then visit our WordPress Page and follow us on facebooktwittertumblrlinkdedin and if you like this article then share this.