Template for specific post of custom post type

I have the CPT “event”. I have created single-event.php.

I want one particular event to use a different template than single-event.

I read elsewhere that this could be done by creating a single-event-[slug].php but I tried it and it does not work. WP uses single-event.php. (I can’t find this in the WordPress documentation, so I’m thinking maybe I misunderstood?)

Is there a way of doing this?

2 s
2

For the templates WordPress uses, please always refer to Template hierarchy scheme in the Codex.

As you can see there, single-{$posttype}-{$slug}.php does not exist, there is only single-{$posttype}.php.

To do what you want, have a look at the filter 'single_template':

add_filter( 'single_template', function( $template ) {
    global $post;
    if ( $post->post_type === 'event' ) {
        $locate_template = locate_template( "single-event-{$post->post_name}.php" );
        if ( ! empty( $locate_template ) ) {
            $template = $locate_template;
        }
    }
    return $template;
} );

After adding this in your functions.php, you can create the file single-event-{$slug}.php and it will be loaded by WordPress.

Leave a Comment