Brain-WP / Cortex

Routing system for WordPress
MIT License
347 stars 20 forks source link

Lost taxonomy term data using query() #6

Closed bruno-barros closed 9 years ago

bruno-barros commented 9 years ago

I made this route to order posts by meta date-init.

Route::add('agenda/agenda_category/{tax}')
    ->methods(['GET'])
    ->requirements(['tax' => '[a-zA-Z0-9-_]{1,}'])
    ->query(function ($matches)
    {
        return [
            'post_type' => 'agenda',
            'orderby'   => 'meta_value_num',
            'order'     => 'ASC',
            'meta_key'  => 'date-init',
            'tax_query' => [
                [
                    'taxonomy' => 'agenda_category',
                    'field'    => 'name',
                    'terms'    => $matches['tax'],
                ]
            ]
        ];

    });

Without this route I can get the taxonomy term by get_query_var('term'), but with this route I can't. Am I missing something? Changing the order of the global query shouldn't alter the global vars used by WordPress.

gmazzap commented 9 years ago

There is no 'term' query variable, because you are setting taxonomy query via 'tax_query' argument.

When you don't use Cortex, WordPress set 'term' variable from the url, so you can get it.

You can do in 2 ways:

$tax_query = reset(get_query_var('tax_query'));
$term = $tax_query[0];

So you get 'tax_query' argument and then the 'terms' argument. This will work for Cortex, but not when you get the page using standard WordPress urls.

If you need a way that works in both cases you can:

global $wp_query;
$term = $wp_query->tax_query->queries[0]['terms'][0];

I understand is not exactly user friendly, bu you can write an helper function to also perform some checks and avoid notices in case the term is not defined:

function first_queried_term() {
    global $wp_query;
    if (isset($wp_query->tax_query) && ! empty($wp_query->tax_query)) {
         return reset(reset($wp_query->tax_query->queries)['terms']);
    }
    return false;
}
bruno-barros commented 9 years ago

All right! Thak you. For a moment a thought Cortex was changing the way WP works.