get_query_var vs global query variables?

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.

Leave a Comment