One common complaint I have observed on the support forums is templates for Custom Post Types. They simply don’t exist and there is no plan to support them.
For example, if you have a post type with the name of
gallery, the recommendation is to create a PHP file in your theme called
single-gallery and code out that template.
However, what if, like pages, you could have a template and have the flexibility of templates within your Custom Post Type?
In this tutorial, I’m going to show you how I created WordPress page templates for Custom Post Types.
Modifying the WordPress Theme
To follow along, you can download the Twenty Twelve Child Theme.
First, let’s activate the child theme.
Here is the directory structure I used to allow post type templates:
I created a folder called cpt-templates and within that folder, I created a folder for each post type: book and gallery. These folders must match the name of the post types you are planning to create. Within each post type folder, I just copied the
full-width.php file into each directory as an example of what’s possible.
We’ll be creating a plugin called CPT Templates. You can download CPT Templates to follow along with this tutorial.
One you have downloaded and activated the plugin, you should see two new post types: Book and Gallery.
Assuming you have the child theme activated and the plugin activated, you should now be able to create a new book or gallery and select a page template for both.
Let’s dive into the plugin code and explain how this all works.
First, the plugin initialization and initial hooks:
The above code initializes the plugin and sets some post types in a class variable.
Post Type Creation
The above creates the post types and registers a meta box callback.
This method is magical in that it scans your theme folder based on post type and returns which templates can be selected.
The above is called from the
template_include hook. It searches the current object for a template, and if it exists, uses it instead of the standard WordPress template.
The above saves the post type as post meta. We use the standard meta keys to be consistent with the naming convention that WordPress uses.
I stole the above from WordPress Core. There wasn’t a way to call it directly, so I chose to include it in the plugin.
As shown above, a Gallery with a template is full-width, while a Gallery with no template shows the default with a sidebar.
You can get as crazy as you want with the above solution, and even start assigning templates to posts if you feel so inclined.
Be sure to also read: How-To Create WordPress Custom Post Type Archive Content With CMB2