Question

Since 3.1 WordPress support multiple taxonomy query. The question is : If I have a two taxonomy query, e.g:

http://localhost:8888/site/?lot-term=australia&story-type=note

how can I determine which template to be used for the query? On the first try, it loads taxonomy-lot-term.php, but after I re install the theme, it loads taxonomy-story-type.php instead.

After some experiment, I found a way to make it use my preferred template file by using a single taxonomy query first (the preferred taxonomy template file) and altering it using query_posts. But I believe there is a better way to do it since it add another SQL query.

Thank you in advance.

Was it helpful?

Solution

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.

OTHER TIPS

I have found another solution to this. When you use the add_action( 'init', 'register_custom_taxonomy', 0 ); hook, make sure you do this in order. When adding the taxonomies, the first one mentioned will be the chosen template.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top