Search code examples
wordpresscustom-post-typecustom-wordpress-pages

Custom template for one specific post in a custom post type in wordpress


I have a little web app, that I want to run within a page in a custom post type on my WordPress site. So I thought to just create a new template to put the specific code for this app there and assign this template to the custom post types page.

Sadly Wordpress is not showing me the template in my cpt.

The template file is called fretfind.php and the first lines contain:

/*  
Template Name: Fretfind 
Template Post Type: guitar
*/

'guitar' is the cpt slug.

Has anyone an idea why it doesn't show me the selecting option for this template. Are there any extra steps for Custom Post Type Templates?

Or is there generally another good practice to have just on one specific wordpress page custom php code? Something like a template for post ID?


Solution

  • If this was a page, you could have used a template file called page-{slug}.php, where {slug} is the slug of the specific page (see here: https://developer.wordpress.org/themes/template-files-section/page-template-files/#page-templates-within-the-template-hierarchy).

    But since we're talking about CPT there is unfortunately only single-{$posttype}.php and no single-{$posttype}-{$slug}.php (see here: https://developer.wordpress.org/themes/template-files-section/custom-post-type-template-files/#custom-post-type-templates)

    However, you can add support for such template files for CPT by adding this code to your theme's functions.php:

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

    And then use the template file single-guitar-myspesificguitarslug.php (where myspesificguitarslug is the slug of the CPT page where you want this template to apply)