Load Custom Post Type Template From Plugin in WordPress

By Richard Webster on 20th December, 2017

What's the problem?

We want to be able to load a custom page template for a custom post type dynamically in our plugin, without needing the user to have a file in their theme folder. Usually you would have a single-my-custom-post.php file somewhere in the theme directory, as a single template for a custom post type. But how do you load a custom template in a plugin?

The Solution

In this example we have a custom post type called my_custom_post_type created in our plugin.

The below code will be in a file that's in your main plugin directory, and in that same directory you will have a folder called "templates". Inside that folder will be your custom page template file.

We need to hook into the single_template filter, check if the current post is our custom post type, and if it is, return our custom template. Easy.

Don't forget to alter the code to your needs, and change the function names to something a little more unique!

add_filter( 'single_template', 'load_my_custom_template', 50, 1 );
function load_my_custom_template( $template ) {

	if ( is_singular( 'my_custom_post_type' ) ) {
		$template = plugins_url( 'templates/my_custom_post_type.php', __FILE__ );
	return $template;

Your comment may be held in moderation

Leave a comment