More

WordPress: Load Custom Post Type Template from Plugin

So while developing a new plugin for restaurant website design platform, I ran into a scenario where I needed to load a custom post type template from a WordPress plugin.

Reason being, is because my plugin was registering a custom post type and I needed a way to load a accompanying custom post type template.

This way the user would not have to load the template via the themes folder which is how you would normally do it.

2 things I want to accomplish.

  • Check is the custom template is in the parent or child theme, in the user wants to overrides the plugin's template
  • If the custom post type template is not present in parent or child theme, then load custom post type template from plugin

See the snippet below.

function load_menu_template($template) {
    global $post;

    if ($post->post_type == "food_menu" && $template !== locate_template(array("single-food_menu.php"))){
        /* This is a "food_menu" post 
         * AND a 'single food_menu template' is not found on 
         * theme or child theme directories, so load it 
         * from our plugin directory
         */
        return plugin_dir_path( __FILE__ ) . "single-food_menu.php";
    }

    return $template;
}

add_filter('single_template', 'load_menu_template');

Glenton
I'm an experience designer. I spend my days and nights on creating designs, writing code, and digital marketing. I specialize in helping small businesses integrate their existing business systems with modern SaaS tools to gain an edge in the marketplace.

Leave a Reply

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

Post a Review

Leave a Reply

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

Login