5

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?

9

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.

| improve this answer | |
  • 1
    thank you! this worked. only changed line 4 to $locate_template = locate_template( "single-event-{$post->post_name}.php" ); – spiral Sep 11 '14 at 12:08
  • np @spiral glad it works. Yes, I've changed that to my answer too. – gmazzap Sep 11 '14 at 12:49
1

Use this code in your functions file for a child theme and change the 8 to the post i.D you want to use the custom single CPT template on.

function get_custom_post_type_template($single_template) {
     global $post;

     if ( is_single('8') ) {
          $single_template = get_stylesheet_directory() . '/custom-cpt-template.php';
     }
     return $single_template;
}
add_filter( 'single_template', 'get_custom_post_type_template' );
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.