3

I am adding a new query string parameter to be passed into the URL so that I can manipulate the REST API responses.

I added this to my functions.php

add_filter('query_vars', function ($vars) {
        $vars[] = 'xyz';
        return $vars;
});

This should make the parameter xyz available in the WP_Query object but it does not.

add_filter('pre_get_posts', function ($query) {
  var_dump($query->query_vars);die;
});

The xyz property is not available in the query_vars however if I dump out the PHP $_GET array, it is there and has the value that I passed in, so I don't know why it wouldn't be making it into the query_vars. Any ideas?

2 Answers 2

1

I'm not sure it quite works like that. Try inspecting $query->public_query_vars instead and I think you'll see it added in there.

The way I usually use it is like this:

add_filter( 'query_vars', 'add_test_query_vars');

function add_test_query_vars($vars){
    $vars[] = "test";
    return $vars;
}

So the same as you but with a named function.

Then I add a rewrite endpoint:

function wpse_243396_endpoint() {
    add_rewrite_endpoint( 'test', EP_PERMALINK );
}

add_action( 'init', 'wpse_243396_endpoint' );

And after that URLs ending /test/ set the query var which I test like this:

global $wp_query;    
if( isset( $wp_query->query['test'] ) ) { }
1
  • Thanks for the response, Andy. I'm not modifying an endpoint, though. Just trying to get it to recognize a query string parameter like. wp-json/wp/v2/posts/?xyz=some_value Commented Oct 20, 2016 at 19:08
0

I think the value would only be present if you add the get-param to the url when trying to preview it ( or specifically set a value for the query-var using $query->set() )

Try adding ?xyz=hello-world to the end of the url you're testing on & you should see hello-world in the dump.

It will also depend on where you dump... maybe try this:

add_filter('query_vars', function ($vars) {
        $vars[] = 'xyz';
        return $vars;
});

then visit: yoursite.com/?xyz=hello-world

function trythis( $wp_query ) {
    if ( $wp_query->is_main_query() && ! is_admin() ) {
        var_dump( $wp_query ); 
        exit;
    }
}
add_action( 'pre_get_posts', 'trythis' );

... & you should see 'xyz'=>'hello-world' in the dump. I don't think query vars are added to wp-query unless they need to be, that'd add unnecessary bloat.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.