How to choose which template to be used for multiple taxonomy query?

I’m not sure if this the best method, and I would like to hear some other suggestions!

This will alter the template to some pre-defined template if two or more taxonomies are being queried. You can hard-code the taxonomies to check or use get_taxonomies:

/*
* Checks to see if more than one of (certain) taxonomies are being queried
* If they are, alters the template to 'my-multitax-template.php' (if it can find it)
*/
add_filter('template_include', 'my_multietax_template');
function my_multietax_template( $template ){

    //Array of taxonomies to check
    $taxes = array('story','lot-term');

    //Or select ALL taxonomies (or pass $args array argument)
    //$taxes=array_keys(get_taxonomies('','names')); 

    //Keep track of how many of the selected taxonomies we're querying
    $count =0;
    global $wp_query;
    foreach ($taxes as $tax){
        if(isset($wp_query->query_vars[$tax] ))
            $count ++;

        if($count > 1){
            //Locate alternative template.
            $alternate = locate_template('my-multitax-template.php');
            if(!empty($alternate)
                $template = $alternate;
            break;
        }
    }
    return $template;
}

Of course ‘my-multitax-template.php’ could in fact be the template name of one of the taxonomies, to give that taxonomy template precedence. Or add additional, more involved logic, if you a querying more than 2 taxonomies and want WordPress to load different templates according to particular cases.

Leave a Comment