Can my WordPress custom templates be in the plugin folder or only in the theme folder?

A WordPress theme I am developing has an integrated custom post type called “albums” which utilizes a few custom templates (archive-albums.php, content-albums.php, etc.). What I want to do is transfer this functionality, along with the template files, into a plugin for the sake of portability.

I transferred the CPT code from the functions.php with success, but when I try to move the template files from the theme folder to the plugin folder, things fall apart. I feel like it should be simple to somehow register the templates so WordPress knows to load them.

Read More

Can my WordPress custom templates be in plugin folder or only theme folder?

Related posts

Leave a Reply

2 comments

  1. Things are falling apart because when you move those files, you’re violating WP’s native template hierarchy. You’ll need to explicitly declare the location of those files. Using the archive as an example, you could add something like this to functions.php (to tell WP to look elsewhere):

    add_filter('template_include', 'include_album_template', 1);
    function include_album_template($template_path) {
    if(get_post_type() == 'albums') {
        if(!is_single()) {
            $theme_file = 'path-to-your-plugin-directory';
            $template_path = $theme_file; 
        }
    }
    return $template_path;
    }
    

    Obviously you’d use your own path, and I wrote this hastily so you might want to refactor.

  2. I have the same issue. I’m already using add_filter ('template_include', ...) problem is that I need to specify a file to return, and in this case being it,index.php. This raises an issue with the theme not running entirely as if installed via themes folder, because what I need is to have WP selecting the appropriate file to render without any conditional logic from my part. So if it is a post it will select the single.php and so on. Another problem raised with this method is that in header.php the call get_header (); ignores the local file header.php and loads the default theme installed file instead.