Skip to content

Instantly share code, notes, and snippets.

@robbiegod
Last active August 28, 2018 16:00
Show Gist options
  • Save robbiegod/7f0a991be30bb12b331b67aeb9127634 to your computer and use it in GitHub Desktop.
Save robbiegod/7f0a991be30bb12b331b67aeb9127634 to your computer and use it in GitHub Desktop.
Wordpress Function: Loads a single-{cat->slug}.php by category slug or single-{post_type}.php custom template by post type. If these don't exist use single.php.
<?php
/**
* single-{category_slug}.php || single-post-type.php || single.php
*
* Gets post cat slug, post type and look matching single- templates.
* If $categories is not empty, get the category slug, and look for single-{$category_slug}.php. If this file doesn't exist then return single.php.
* If $categories is empty, then check the post_type. If its not equal to post, then we are using a custom post type. Look for
* single-{$post_type}.php. If this file doesn't exist then use single.php.
* If $categories is empty and post_type is equal to post then use single.php.
*
**/
function add_custom_single_template( $display_custom_single_template ) {
$object = get_queried_object();
$post_type = $object->post_type;
$categories = get_the_category($object->ID);
if( !empty( $categories ) ) {
foreach($categories as $category) {
$category_slug = $category->slug;
}
$display_custom_single_template = locate_template("single-{$category_slug}.php");
if( empty($display_custom_single_template) ) {
$display_custom_single_template = locate_template("single.php");
}
} else if( $post_type !== 'post' ) {
// Locate the post_type single template
$display_custom_single_template = locate_template("single-{$post_type}.php");
if( empty($display_custom_single_template) ) {
$display_custom_single_template = locate_template("single.php");
}
} else {
// If no category, then just use the standard single.php template
$display_custom_single_template = locate_template("single.php");
}
if( file_exists( $display_custom_single_template ) ) {
return $display_custom_single_template;
}
}
add_filter( 'single_template', 'add_custom_single_template', 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment