gallery, the recommendation is to create a PHP file in your theme called
single-galleryand 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 ThemeIn this example, I’m going to create a child theme of Twenty Twelve. 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.phpfile into each directory as an example of what’s possible.
The PluginWe’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.
Plugin CodeLet’s dive into the plugin code and explain how this all works.
Plugin InitializationFirst, the plugin initialization and initial hooks: The above code initializes the plugin and sets some post types in a class variable.
Post Type CreationThe above creates the post types and registers a meta box callback.
Template SelectionThis method is magical in that it scans your theme folder based on post type and returns which templates can be selected.
Template RenderingThe above is called from the
template_includehook. It searches the current object for a template, and if it exists, uses it instead of the standard WordPress template.