• 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;
    }

Viewing 3 replies - 1 through 3 (of 3 total)
  • Here’s a simpler version of what you’re trying to do:

    add_filter( 'single_template_hierarchy', 'my_single_hierarchy' );
    
    function my_single_hierarchy( $templates ) {
    
        if ( ! is_singular( 'post' ) ) {
            return $templates;
        }
    
        $new_templates = [];
    
        foreach ( get_the_category( get_queried_object_id() ) as $category ) {
            $new_templates[] = "single/single-{$category->slug}.php";
        }
    
        return [
            ...$new_templates,
            ...$templates
        ];
    }
    Thread Starter MyWorldz

    (@myworldz)

    Thank you so much. Really appreciate it!!

    Thread Starter MyWorldz

    (@myworldz)

    Sorry to bother you but I have another question that’s a bit related.

    Is it possible to use the same template for a category and a single page. So for example, I have a blog category and I want to use the same template for the single page as I use for the category. This way I don’t have to create a single-blog.php and a category-blog.php.

    How would I do that please?

    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Create Custom Single Post Templates by Category’ is closed to new replies.