Any wordpress theme comes with a single post, page and archive template. None of these templates may be suitable for you if are creating your own custom post for event, products, etc.
In such cases we need to create our own templates
There are 2 ways to create custom post type template files in wordpress
Method 1: Create custom post type template files within your Child Theme folder
Suppose your custom post type is event. You would create below files in your child theme directory.
Once the above files are created they will be automatically picked for your events single post and archive posts. So whatever your custom post type is, the template file names should be as named as below
It is very easy to create and modify your custom post type template files
- The template files are not within your plugin. So if you want to install the plugin on some different website you need to remember to get the template files from the theme directory as well.
- If later you do not want this plugin anymore then disabling the plugin is not sufficient. You need to remove the above template files from the themes directory.
- This method can get messy as later it becomes difficult to remember why certain templates were created (unless you properly document them).
Method 2: Create custom post type template files in your plugin folder
This is assuming you have created your custom post by creating a plugin for it. (Note: Ideally a custom post should be created using a plugin anyway due to various advantages of plugins).
In this method copy the single.php and archive.php files from your themes directory and paste them in your plugin directory. If you wish you can create a subfolder named as templates inside your plugin and paste this files in the templates subfolder.
Now add below code in your plugin file
$post_types = array('my_custom_post');
if ( is_post_type_archive( $post_types ) )
$template = plugin_dir_path(__FILE__) . 'archive.php';
$template = plugin_dir_path(__FILE__) . 'single.php';
- All your code related to the custom post remains in a single directory. So it is much easier to maintain.
- You can move the plugin folder anywhere along with the templates
- Becomes easier to activate or deactivate a plugin