Add a Custom Post Type Template in WordPress 4.7

WordPress 4.7 brings a new feature in the ability to add a Custom Post Type template in a similar way a Page Template is added.

A page template can be added by creating a specific file page-{id}.php or page-{slug}.php file, the problem with this approach is that it is not reusable for other pages, so a more global template can be create by also creating a php file in your themes folder with the following header.

As long as the header info is in place you can name the file what you like but try and keep some sane naming conventions for easier file management.

<?php
/*
Template Name:News Page
*/
?>

 

custom wordpress page templae
Then the template is available under from the post editor under the  Page Attributes > Template metabox.

To add a Custom Post Type template in WordPress 4.7  you add in an extra line Template Post Type to the header info and add in the post type name, either a regular post or the registered name of the Custom Post Type.

 

<?php
/*
Template Name:News Page
Template Post Type: post, page, portfolio, event
*/
?>

 

wordpress-custom-post-type

So now the template is available to not only posts and pages but also to CPTs Portfolio and Event

One caveat is that on versions of WordPress pre 4.7, the templates will show under the Page template list – this can be hidden using the theme_page_templates filter…

/**
 * Hides the custom post template for pages on WordPress 4.6 and older
 *
 * @param array $post_templates Array of page templates. Keys are filenames, values are translated names.
 * @return array Filtered array of page templates.
 */
function makewp_exclude_page_templates( $post_templates ) {
    if ( version_compare( $GLOBALS['wp_version'], '4.7', '<' ) ) {
        unset( $post_templates['templates/my-full-width-post-template.php'] );
    }
 
    return $post_templates;
}
 
add_filter( 'theme_page_templates', 'makewp_exclude_page_templates' );

Ref & Ref

2 Comments

  1. Hashim Warren on February 20, 2017 at 3:53 am

    Suuuuper helpful. Thank you.

    I’m using Genesis as my theme and unfortunately it looks like they’re not taking advantage of this new feature. So, I need to do it myself.

    • Bjarni Wark on March 16, 2017 at 10:00 am

      Thanks for sharing that handy tip about.CPT’s and templates.

Leave all Comment