get_query_var() not working in pre_get_posts

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!

Related posts

Leave a Reply

1 comment

  1. 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,

    Kuchenundkakao