Using query_vars filter

I am trying to link out from the WP admin to view posts in a specific way.
The url structure for this is example.com/post123/?my-preview=456

/post123/ is the regular permalink for a post. The ?my-preview=456 allows a section of that post to retrieve information based off of the my-preview value.

Read More

I understand that WP strips $_GET parameters from the url, so I tried using add_filter('query_vars','my_query_vars'); and

function my_query_vars($query_vars){
    $query_vars[] = 'my-preview';
    return $query_vars;
}

On the actual section where I need to get that value, I tried using:

global $wp_query;
var_dump($wp_query->query_vars);

Even with a url like the example above, the ‘my-preview’ pair is nowhere to be found in the $wp_query->query_vars array.

Am I not doing the correct steps to register an additional query_var for use later on? If I am, why does it not stick around?

EDIT:
I have also tried:
add_action('init', 'add_query_vars');

with

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

and wp_die(var_dump(get_query_var('my-preview'))); gives string(0) ""

Related posts

1 comment

  1. The query vars filter is unnecessary for what you’re doing here, as you’re not using it in a query. Adding it to the URL as a GET parameter will not make it appear in the array of query vars, as there’s no mechanism that converts a GET var to a query var, you’ve only ensured it won’t be removed if it’s added to the query.

    As long as the GET var is unique and not reserved by WordPress, there’s nothing that should prevent setting and then accessing a GET var via normal means: $_GET['my-preview'].

Comments are closed.