3

I have query vars defined in functions.php using:

add_filter('init', 'add_query_vars');

function add_query_vars() {
    global $wp;
    $wp->add_query_var('profession');
}

Until now, to retrieve the query var in page templates, I have been using $profession = get_query_var('profession');. A similar example $paged = get_query_var('paged'); is also shown for the $paged variable on Codex page for get_query_var(). However, today I learnt that the query variables are accessible as global variables. All I have to do is declare global $profession; and I can start using the value of the variable anywhere within the template. This to me appears to be a much better way of accessing the query vars without the overheads of nested functions of get_query_var().

Is there a good reason to use get_query_var() to fetch the query vars instead of accessing them as global variables? If not, then why does get_query_var() even exists?

1 Answer 1

6

get_query_var() is a wrapper for $wp_query->get($var);. But the global $wp_query is not always identical to the one set up during the request. That’s the main problem with query_posts().
And other plugins can overwrite these variables unintentionally too. I have seen plugins putting $i into the global namespace …

And the return values are different:

  • $GLOBALS['missing_var'] is NULL if there is no such variable. The strict type check is: if ( NULL !== $GLOBALS['missing_var'] ).
  • get_query_var('missing_var'); is an empty string if that variable doesn’t exist. The strict type check is: if ( '' !== get_query_var('missing_var').

When other programmers have to work with your code, they can always follow get_query_var() to see the fallback value. That’s not possible with global variables.

And then there are plans to reduce the amount of global variables in WordPress. Use the API (the function) and you are probably safe. Accessing global variables on the other hand might lead to trouble.

2
  • 6
    I'd also add that when given a choice between the global namespace and something else, it's usually best not to use the global namespace as it gets messy and it's not clear where the variable is coming from
    – Tom J Nowell
    Commented Apr 18, 2013 at 14:48
  • Clear and defined explanation. Exactly what I was looking for. Thx.
    – John
    Commented Apr 18, 2013 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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