15

I am busy developing a WordPress application and I need to be able to pass url parameters using WordPress functions. I use add_query_arg() function to add a url parameter. However, when I try to get the passed value in the other page using get_query_var() nothing gets returned. When I used $_GET['var_name'] the values gets returned.

What is the possible cause of this situation? I can successfully add arguments to the url but I am not able to access them.

4 Answers 4

24

I managed to get the get_query_var() function to work. To use the two functions successfully, you need to add the query vars to wordpress's query vars array. Here is a code sample.

function add_query_vars_filter( $vars ){
  $vars[] = "query_var_name";
 return $vars;
}

//Add custom query vars
add_filter( 'query_vars', 'add_query_vars_filter' );

Now you can use get_query_var() and add_query_arg() as follows:

Add the query var and value

add_query_arg( array('query_var_name' => 'value'), old_url );

Get the query var value

$value = get_query_var('query_var_name');

More information and code samples can be found at the Codex: get_query_var and add_query_arg

Sign up to request clarification or add additional context in comments.

1 Comment

this answer doesn't explain where one would call add_filter, add_query_arg, etc. It could be considerably improved with more detail.
8

To troubleshoot, what variables are being used in the request use following code

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

1 Comment

Help with troubleshooting and gathering debugging details does not constitute posting an answer. If you need more details, post a comment under the question. Your non-resolving guidance should have been a comment.
3

If you check out the Codex, you'll see you actually need to do some fiddling to get WP to start reading your query string.

Codex (under Custom Query Vars)

Excerpt:

In order to be able to add and work with your own custom query vars that you append to URLs (eg: "mysite com/some_page/?my_var=foo" - for example using add_query_arg()) you need to add them to the public query variables available to WP_Query. These are built up when WP_Query instantiates, but fortunately are passed through a filter 'query_vars' before they are actually used to populate the $query_vars property of WP_Query.

Comments

0

get_query_var() only retrieves public query variables that are recognized by WP_Query. This means that if you create your own custom URLs with their own query variables, get_query_var() will not retrieve them without some further work.

Documentation

Comments

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.