Categories
WordPress

WordPress Plugin Template redirect custom post, page, taxonomy

Here is example of how we can redirect to custom templates in wordpress plugin with page name, custom post type, custom taxonomies etc 

 

<?php
add_action("template_redirect", 'my_theme_redirect');

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

 // A Specific page by title / name

 if ($wp->query_vars["pagename"] == 'agenda')
 {
 $templatefilename = 'page-event-list.php';
 if (file_exists(TEMPLATEPATH . '/' . $templatefilename))
 {
 $return_template = TEMPLATEPATH . '/' . $templatefilename;
 }
   else
 {
 $return_template = $plugindir . '/templates/' . $templatefilename;
 }

 do_theme_redirect($return_template);
 }

 // A Specific Custom Post Type

 if ($wp->query_vars["post_type"] == 'events')
 {
 $templatefilename = 'single-event.php';
 if (file_exists(TEMPLATEPATH . '/' . $templatefilename))
 {
 $return_template = TEMPLATEPATH . '/' . $templatefilename;
 }
   else
 {
 $return_template = $plugindir . '/templates/' . $templatefilename;
 }

 dmk_redirect_to_login_if_not_logged_in();
 do_theme_redirect($return_template);

 // A Custom Taxonomy Page

 }
 elseif ($wp->query_vars["taxonomy"] || is_tax('location') == 'location')
 {
 $templatefilename = 'taxonomy-event_location.php';
 if (file_exists(TEMPLATEPATH . '/' . $templatefilename))
 {
 $return_template = TEMPLATEPATH . '/' . $templatefilename;
 }
   else
 {
 $return_template = $plugindir . '/templates/' . $templatefilename;
 }

 do_theme_redirect($return_template);
 }
 }

// Function includes file and does redirection

function do_theme_redirect($url)
 {
 global $post, $wp_query;
 if (have_posts())
 {
 include ($url);

 die();
 }
   else
 {
 $wp_query->is_404 = true;
 }
 }

By milind

Milind is a Senior WordPress Engineer at rtCamp.
WordPress Ecosystem Contributor and AMP Support Engineer.

One reply on “WordPress Plugin Template redirect custom post, page, taxonomy”

Comments are closed.