Created
October 31, 2013 00:38
-
-
Save danielmcclure/d379db7e3548503d77ed to your computer and use it in GitHub Desktop.
Replace Page Template from Within WordPress Plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Template Replacement | |
add_action("template_redirect", 'custom_template_redirect'); | |
function custom_template_redirect() { | |
global $wp; | |
$plugindir = dirname( __FILE__ ); | |
//A Custom Post Type | |
if ($wp->query_vars["post_type"] == 'product') { | |
$templatefilename = 'single-product.php'; | |
if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { | |
$return_template = TEMPLATEPATH . '/' . $templatefilename; | |
} else { | |
$return_template = $plugindir . '/themefiles/' . $templatefilename; | |
} | |
do_theme_redirect($return_template); | |
//A Custom Taxonomy | |
} elseif ($wp->query_vars["taxonomy"] == 'product_categories') { | |
$templatefilename = 'taxonomy-product_categories.php'; | |
if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { | |
$return_template = TEMPLATEPATH . '/' . $templatefilename; | |
} else { | |
$return_template = $plugindir . '/themefiles/' . $templatefilename; | |
} | |
do_theme_redirect($return_template); | |
//A Standard Page | |
} elseif ($wp->query_vars["pagename"] == 'somepagename') { | |
$templatefilename = 'page-somepagename.php'; | |
if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { | |
$return_template = TEMPLATEPATH . '/' . $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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment