Create Custom Single Post Templates by Category
-
Hi there,
I’m trying to create custom single post templates by category. I used the code below but the appropriate page is not displaying. It is defaulting to the index.php.
1) I created a folder call “single”
2) I have a category called “news”, so I add a file in the single folder called “single-news.php”
What am I doing wrong please?// Creating Custom Single Post Templates by Category
/* 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->slug . '.php'))
return SINGLE_PATH . '/single-' . $cat->slug . '.php';
elseif(file_exists(SINGLE_PATH . '/single-' . $cat->term_id . '.php'))
return SINGLE_PATH . '/single-' . $cat->term_id . '.php';
endforeach;
}
- The topic ‘Create Custom Single Post Templates by Category’ is closed to new replies.