Page Template for any Post Type in WP 4.7
Support for page templates ("page" post type) has been unchanged for 12 years. And it helped developers to conveniently create templates for pages, but it has always been limited to the page post type. However, with WordPress version 4.7 this situation has changed and you can now create templates for any post type.
Templates for 'page' Post type
I already wrote an article on how to create templates for page post type using different methods. Let me remind you one of the methods: to create a page template, you need to create a file with any name in your WordPress theme (for example, `my-template.php') and specify in its header comment (metadata) that this file is a template:
<?php /* Template Name: My page template */ ?> <!-- Here is thw html/php template code -->
A template file can be placed even in a subfolder of the theme, WordPress still will find it. For example, you can create a folder with 'templates' name in your theme, and put all created template files there.
After that, on the page for editing or adding a new page in the Admin Panel, you will be able to select this template on the 'Page Attributes' section.
Templates for any Post type
Since WordPress version 4.7 the pages template functionality has been expanded to any posts types.
To specify that the template file you are creating is supported to be for a specific post type, you must specify the name of the post type in the file's header comment (metadata) under the Template Post Type: string. Multiple post types can be specified separated by a comma.
For example, let's create a template that supports three post types: post, page, product. To do this add a php comment at the beginning of the file:
<?php /* Template Name: My page template Template Post Type: post, page, product */ // … other template code
Now on the page for editing or adding a new page in the Admin Panel of the post types: post, page, product, we can select our template «My page template».
Notes for Developers
If at least one template exists for a post type, the Metabox
Post Attributesappears automatically on the edit post page. It is not necessary to enable support of 'page-attributes' when registering a post type.
- The Metabox title
Post Attributescan be changed in parameter label > attributes when registaring a post type.