WordPress: Different single post templates

In WordPress, single.php displays a different layout for single posts. This template applies to all posts.

To display different layout for different criteria, such as post types, category etc, make use of single_template filter.

This example shows a different layout for a specific category, falls back to default if not exists. File naming convention for the template is single-<category_slug>.php.

In functions.php:

function single_category_template($template) {
    $cat = get_the_category();
    $template = locate_template(array('single-' . $cat[0]->slug . '.php', 'single.php'));
    return $template;
add_filter('single_template', 'single_category_template');

Note line 3: use locate_template() instead using physical path. It automatically ‘Retrieve the name of the highest priority template file that exists.’ Useful for implementing child themes.

Leave a Reply

Your email address will not be published. Required fields are marked *