Display Custom Post Type Page Template from Plugin

Custom post type page template from plugin

As a custom WordPress plugin developer I have to create custom post types (CPT) for most of my projects. And most of those CPTs require their own theme layout to display in frontend.

This can be done easily with the reference of WordPress template hierarchy if I am creating the complete project, like developing the theme also. I can create single-{CPT name}.php file in theme directory to render the layout in frontend and archive-{CPT name}.php for archive page of the custom post type.

But if I am not developing the theme and from just plugin I have to have a particular layout for a custom post type irrespective of theme. Then I have to do it within the plugin.

Here I am going to show you the code snippet which I use to create theme layout for CPT from plugin without touching any code from theme.

By this code snippet you can define single page template of your CPT from your plugin. I prefer to have all my custom theme pages within a directory called “templates” and here also I have done that within the plugin directory.

This code snippet will help you to render CPT archive template from plugin.

Here is a explanation of the code.

At first we have added WP filter for each of this snippet. These filters are running before the rendering of any pages. While a visitor is visiting on a single page or archive page, then this code will run and WordPress will check for the function which is mentioned there.

Then within those functions we are checking for our custom post type and if its matches then we are returning our own template file.

Hope this code will help you in your next project.

Happy coding.

Leave a Reply

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