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 :

function customtypes_redirect_register($slug, $file, $overwrite=true)
    if(!get_option('customtypes_redirect')) {
	$redirects = array();
    } else {
	$redirects = (array) json_decode(get_option('customtypes_redirect'));
    if(($overwrite===false)  && $redirects[$slug]) return;
    $redirects[$slug] = $file;
    update_option('customtypes_redirect', json_encode($redirects));

…then the actual redirect hooked into template_redirect :

add_action("template_redirect", 'customtypes_redirect');

function customtypes_redirect()
	if(!get_option('customtypes_redirect')) return;
        $slug_templates = (array) json_decode(get_option('customtypes_redirect'));

	global $wp;
	global $wp_query;
	global $post;

//if it aint a post or page, check if the post_type has a redirect, if the file exists, redirect and quit
	if (isset($wp->query_vars["post_type"]) && $wp->query_vars["post_type"] != 'post' && $wp->query_vars["post_type"] != 'page') :
		if(!$slug_templates[$wp->query_vars["post_type"]]) return;
		if(!file_exists($slug_templates[$wp->query_vars["post_type"]])) return;

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

add_action('init', 'add_customtype_redirects');
function add_customtype_redirects() {
    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 *