Add Template To Custom Post Type In A Plugin

This probably falls in the not the best idea for all applications category, depending on how you separate and manage functionality.
The situation I used this in required that I create a plugin (you could also use your theme’s functions.php file) for a custom post type.
I wanted the custom post type to have a template different from my posts, or other custom post types already added to the project.

The solution that I came to was to use an if statement, a filter, and WordPress’ built in functions single_template & archive_template. The if statement checks to see if the post type is equal to the custom post type, and then sets the single or archive template. The filter then adds the function.


//route single-template
function rjs_single_customtype($single_template){
  global $post;

     if ($post->post_type == 'customtype' ) {
          $single_template = plugin_dir_path(__FILE__) . 'single-customtype.php';
     }
     return $single_template;
}

//route archive-template
function rjs_archive_customtype($archive_template){
	  global $post;

     if ($post->post_type == 'customtype' ) {
          $archive_template = plugin_dir_path(__FILE__) . 'archive-customtype.php';
     }
     return $archive_template;
}

add_filter('single_template','rjs_single_customtype');
add_filter('archive_template','rjs_archive_customtype');

Leave a Reply

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