wordpress custom post types : template location

Now let me explain why this makes intuitive sense.
(Prof. Larry Wasserman)

I wanted some hands-on with wordpress custom types and stumbled upon the usual quotes database, so one of my blogs has become a plugin quotes site with xml-rpc api. And ran into a minor geek problem : WordPress seems to want to pick mytheme/single-customtype.php or mytheme/single.php as template.

I don’t want to loose the custom template when I switch themes. So I added a standard redirect function using an array(‘slug’, ‘redirect-to-template’) in the blog options table.

First a function to register the redirect in the blog options table :

  1. function customtypes_redirect_register($slug, $file, $overwrite=true)
  2. {
  3.     if(!get_option('customtypes_redirect')) {
  4.  $redirects = array();
  5.     } else {
  6.  $redirects = (array) json_decode(get_option('customtypes_redirect'));
  7.     }
  8.     if(($overwrite===false)  && $redirects[$slug]) return;
  9.     $redirects[$slug] = $file;
  10.     update_option('customtypes_redirect', json_encode($redirects));
  11. }

…then the actual redirect hooked into template_redirect :

  1. add_action("template_redirect", 'customtypes_redirect');
  2.  
  3. function customtypes_redirect()
  4. {
  5.  if(!get_option('customtypes_redirect')) return;
  6.         $slug_templates = (array) json_decode(get_option('customtypes_redirect'));
  7.  
  8.  global $wp;
  9.  global $wp_query;
  10.  global $post;
  11.  
  12. //if it aint a post or page, check if the post_type has a redirect, if the file exists, redirect and quit
  13.  if (isset($wp->query_vars["post_type"]) && $wp->query_vars["post_type"] != 'post' && $wp->query_vars["post_type"] != 'page') :
  14.   if(!$slug_templates[$wp->query_vars["post_type"]]) return;
  15.   if(!file_exists($slug_templates[$wp->query_vars["post_type"]])) return;
  16.                 include($slug_templates[$wp->query_vars["post_type"]]);
  17.       die();        
  18.  endif;
  19. }

Now I just have to register the redirect from the plugin file :

  1. add_action('init', 'add_customtype_redirects');
  2. function add_customtype_redirects() {
  3.     customtypes_redirect_register('quote', ABSPATH . 'wp-content/plugins/'.basename( dirname( __FILE__ ) ) ."/my-customtype-template.php"); }

…and I can keep my templates in the plugin dir, and switch themes as much as I want.

Posted in juust, wordpress.

Leave a Reply

Your email address will not be published. Required fields are marked *