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.

  • single-event.php
  • archive-event.php

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

  • single-{post-type}.php
  • archive-{post-type}.php

Refer WordPress Theme Handbook

Advantages:

It is very easy to create and modify your custom post type template files

Disadvantages:

  1. 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.
  2. 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.
  3. 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

Advantages

  1. All your code related to the custom post remains in a single directory. So it is much easier to maintain.
  2. You can move the plugin folder anywhere along with the templates
  3. Becomes easier to activate or deactivate a plugin

 

Leave a Reply

Your email address will not be published. Required fields are marked *