David Ogilo

menu search

Loading a post template based on post type and ID in WordPress

Ever wondered how you can load a template for a post based on its ID or post type apart from using a default template that handles all type of posts? Well, there is an easy way! All you need to do is add a few lines in the functions.php file of your site theme. An explanation is shown below:

add_filter( 'single_template', 'singleTemplate' );
 
function singleTemplate( $template )
{
	global $post;
 
	if  ( $post->post_type == 'post' )
		$replace = 'post-';
 
	$replace .= $post->ID;
 
	$newTemplate = preg_replace( '/(.*)\.php$/', '-'. $replace . '.php', $template );
 
	if ( file_exists( $newTemplate ) )
		return $newTemplate;
 
	return $template;
}

The template file will be in the format single-{post_type}-{ID}.php

Tags: , , , ,

Old school browser detected!

Your browser is out of date, which means you can't use any of the site's required features. You can either upgrade your browser or switch to either Mozilla Firefox or Google Chrome