Skip to content
Advertisement

Loading Templates from a plugin in WordPress

I’m trying to make my first plugin and I got stuck. Here is the idea. When my plugin is activated it will create one post type and two taxonomies for that post type (in my case the post type name is ‘Ads’). Also, I created two template pages, one to display the listing of all ads post type articles and the other for a single page for the same post type.

Now my problem is how to tell WordPress to look for the templates from a plugin folder rather than the theme folder when the plugin is active.? Is it something I can do in the plugin file or I have to create another file for this purpose?

Advertisement

Answer

This should do what you are looking for:

First, this hook to tell WordPress which is your single CPT template in your plugin

From this answer you get the single_template hook and how to load it.

Define a constant to replace “plugin_dir_path( FILE )” if you use it elsewhere in your plugin, like this:

define('YOUR_PLUGIN_DIR_PATH', trailingslashit(plugin_dir_path( __FILE__ )) );

https://wordpress.stackexchange.com/questions/17385/custom-post-type-templates-from-plugin-folder

 function load_single_ad_template( $template ) {
       
 global $post;
    
        if ( 'ads' === $post->post_type && locate_template( ['single-ads.php'] ) !== $template ) {
            /*
             * This is an 'ads' post
             * AND a 'single ad template' is not found on
             * theme or child theme directories, so load it
             * from our plugin directory from inside a /templates folder.
             */
            return YOUR_PLUGIN_DIR_PATH . 'templates/single-ads.php';
        }
    
        return $template;
    }
    
    add_filter( 'single_template', 'load_single_ad_template', 10, 1 );

And then for the ads archive template, the ‘archive_template’ hook, like this:

function load_archive_ads_template( $archive_template ) {
     global $post;

     if ( is_post_type_archive ( 'ads' ) ) {
          $archive_template = YOUR_PLUGIN_DIR_PATH . 'templates/archive-ads.php';
     }
     return $archive_template;
}

add_filter( 'archive_template', 'load_archive_ads_template', 10, 1 ) ;

Official documentation:

https://developer.wordpress.org/reference/hooks/type_template/ https://codex.wordpress.org/Plugin_API/Filter_Reference/archive_template

This is untested, but should work, however, let me know.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement