WP – Use file in plugin directory as custom Page Template?

You can do this with the template_redirect hook. Here’s my code to manually replace the template for a custom post type with one in the theme if there isn’t one in the template folder. Put this in your plugin file and then put a folder underneath your plugin called themefiles with your default theme files.

//Template fallback
add_action("template_redirect", 'my_theme_redirect');

function my_theme_redirect() {
    global $wp;
    $plugindir = dirname( __FILE__ );

    //A Specific Custom Post Type
    if ($wp->query_vars["post_type"] == 'product') {
        $templatefilename="single-product.php";
        if (file_exists(TEMPLATEPATH . "https://stackoverflow.com/" . $templatefilename)) {
            $return_template = TEMPLATEPATH . "https://stackoverflow.com/" . $templatefilename;
        } else {
            $return_template = $plugindir . '/themefiles/' . $templatefilename;
        }
        do_theme_redirect($return_template);

    //A Custom Taxonomy Page
    } elseif ($wp->query_vars["taxonomy"] == 'product_categories') {
        $templatefilename="taxonomy-product_categories.php";
        if (file_exists(TEMPLATEPATH . "https://stackoverflow.com/" . $templatefilename)) {
            $return_template = TEMPLATEPATH . "https://stackoverflow.com/" . $templatefilename;
        } else {
            $return_template = $plugindir . '/themefiles/' . $templatefilename;
        }
        do_theme_redirect($return_template);

    //A Simple Page
    } elseif ($wp->query_vars["pagename"] == 'somepagename') {
        $templatefilename="page-somepagename.php";
        if (file_exists(TEMPLATEPATH . "https://stackoverflow.com/" . $templatefilename)) {
            $return_template = TEMPLATEPATH . "https://stackoverflow.com/" . $templatefilename;
        } else {
            $return_template = $plugindir . '/themefiles/' . $templatefilename;
        }
        do_theme_redirect($return_template);
    }
}

function do_theme_redirect($url) {
    global $post, $wp_query;
    if (have_posts()) {
        include($url);
        die();
    } else {
        $wp_query->is_404 = true;
    }
}

Leave a Comment