How to unset a set query variable?

My theme file, multiple times over, passes sets a variable to a template part used in a subsequent template part file via set_query_var, like so…

set_query_var('feature_id', array(143866));
set_query_var('tax_meta_value',  'Payments');
get_template_part('partials/page-blocks/block_tag_new');

set_query_var('tax_meta_value',  'Venture Capital');
get_template_part('partials/page-blocks/block_tag_new');

In the template part, the variable is plucked out, using get_query_var, as $feature_id.

The only problem is – in the second instance here, for example – the template part still retains a memory of the first feature_id value passed above.

When I call the template part in the second instance, how do I ensure that no feature_id value is resident, since none is passed?

Do I need to do something like set the ensuing $feature_id, within the template part file, as global and unset it? Or do that but in the calling file, or something else?

1 Answer
1

When I call the template part in the second instance, how do I ensure
that no feature_id value is resident, since none is passed?

I’m afraid you misunderstood what set_query_var really does. It doesn’t pass anything and it doesn’t work only for the next get_template_part call.

OK, so what does it really do? From docs:

Set query variable.

And here’s its code:

function set_query_var( $var, $value ) {
    global $wp_query;
    $wp_query->set( $var, $value );
}

So now everything should be clear. So let’s take a look at your original code:

set_query_var('feature_id', array(143866));  // <- sets query var called feature_id to 143866
set_query_var('tax_meta_value',  'Payments');  // <- set query var called tax_meta_value to Payments
get_template_part('partials/page-blocks/block_tag_new');

set_query_var('tax_meta_value',  'Venture Capital');  // <- sets tax_meta_value to Venture Capital 
// feature_id is still 143866, because it hasn't been changed
get_template_part('partials/page-blocks/block_tag_new');

If you want to unset the query var, you can set it to false/NULL:

set_query_var('feature_id', false);

Leave a Comment