WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using the pre_get_posts hook to order the main query on all my custom post type / taxonomy pages using a custom meta value. As part of the logic, I am trying to determine which taxonomy is currently being displayed by using get_query_var('taxonomy'), however no matter what I try, it keeps returning a blank string:

function sort_query($query)
    if (is_tax()){
        echo get_query_var('taxonomy'); // Empty
        echo get_query_var($query->query_vars['taxonomy']); // Empty
add_action('pre_get_posts', 'sort_query');

Any help would be greatly appreciated; thanks!

share|improve this question
Are you sure is_tax is working and what you want to use? – Wyck Jan 15 '13 at 17:41
@Wyck As far as I can tell based on limited testing it is working as expected; however I am open to alternatives. Basically need a way to capture the tax and apply different ordering based on it. – dSquared Jan 15 '13 at 18:37
I am also struggling with a similar situation. Some plugin is executing query_posts() but when that query hits my pre_get_posts action, global $wp_query and $q parameter are different. get_query_var check $wp_query and returns empty. Looking at query_posts() source, it unsets and re-sets $wp_query, so how can $wp_query stay something old in my action? – lkraav Jan 25 '13 at 18:52
Just a pro-tip - don't use global template tags in a pre_get_posts hook - use the method of the query instance i.e. $query->is_tax() – TheDeadMedic Nov 4 '15 at 12:54

Did you try this?

function sort_query($query)
    if ($query->is_tax() && $query->is_main_query()){
        echo $query->query_vars['taxonomy']; 
        $query->set( 'orderby', 'post_title' );
        $query->set( 'order', 'ASC' );
        //do other stuff
add_action('pre_get_posts', 'sort_query');

Happy Coding,


share|improve this answer
As AcidX suggested, try $query->tax_query->queries[0]['taxonomy'] - no matter what the query args where, WP_Query will always parse them into a tax query, so this should be a surefire way to get the (primary) taxonomy that was queried. – TheDeadMedic Nov 4 '15 at 12:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.