For some reason that’s not quite clear, when I add custom query_vars, they become available everywhere without the need of an accessor like global or get_query_var()

// if your url contains the var http://example.com?document_id=99
// and you add it to $query_vars...
<?php
function filter__query_vars( $query_vars ) {
  $query_vars[] = 'document_id';
  return $query_vars;
}
add_filter( 'query_vars', 'filter__query_vars' );

// you can reference it anywhere.
/* single.php */
<?php
echo $document_id; // outputs 99. wtf?

Why does this work?

1 Answer
1

Within the WP::parse_request() method (src) we locate the query_vars filter:

$this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );

and within WP::register_globals() we can see why it becomes globally accessible (src):

// Extract updated query vars back into global namespace.
foreach ( (array) $wp_query->query_vars as $key => $value ) {
    $GLOBALS[ $key ] = $value;
}

where the global $Wp_query has been fed with the query vars from the global $wp object.

Leave a Reply

Your email address will not be published. Required fields are marked *