1

I would like to $_GET a parameter in the URL, for that I read I have to use query_vars. First I added the following lines to functions.php:

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

after that:

if(get_query_var('getvar')) {
    die('DIE');
}

If I type domain.com/?getvar=1, nothing happens. Where is the problem?

  • I just copied the code to header.php, and it works. What's the problem with the functions.php? – Tina88 Jun 29 '14 at 12:27
1

Your filter:

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

Is correct. When WordPress starts assembling the list of query variables, this function will add 'getvar' to the list.

But then you immediately check if the variable is set before it reaches that point. The query_vars filter hasn't happened yet. This suggests your understanding of events/filters is incomplete. When you add the filter, it doesn't execute what's inside, in the same way that if I tell you to eat food once you've paid, you wait until you've paid to eat it, you don't immediately eat it.

So:

  1. You tell WordPress to execute a function when 'query_vars' filter happens
  2. You check if the illegal query var 'getvar' is present
  3. Later, the 'query_vars' filter happens and that function'getvar' is made a legal safe query variable
  4. Nothing is done with this query variable

So you need to check for the query var after the function is executed, just being further down the file doesn't do that. you should hook into an action such as init and perform your check there.

| improve this answer | |
  • Any chance of an example @Tom J Nowell ? – AdamJones Nov 21 '16 at 23:45
  • @AdamJones how to hook into the init hook is beyond the scope of my question, and covered in much greater detail elsewhere. If you're looking for something you can copy paste and tweak a value here or there then you're out of luck, and I strongly recommend you look up how actions and filters work ( they're a major part of WordPress basics and easy to learn ) – Tom J Nowell Nov 22 '16 at 2:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.