Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress get_query_var()

Tags:

php

wordpress

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.

like image 887
Themba Clarence Malungani Avatar asked Dec 04 '13 15:12

Themba Clarence Malungani


People also ask

What is Get_query_var in WordPress?

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 (see below).

What is WP_ query-> query_ vars?

$query is an array with the values passed when WP_Query is called, your custom values. $query_vars is an array with all the parameters supported by WP_Query , including the parameters usen when WP_Query was called and the rest of the parameters with the default value.

How do I get the value of a query string in WordPress?

To get a vars from the query string you can use PHP's $_GET['key'] method. Depending on what you are doing, you can also use get_query_var('key') , this function works with parameters accepted by the WP_Query class (cat, author, etc).


1 Answers

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

like image 150
Themba Clarence Malungani Avatar answered Sep 20 '22 05:09

Themba Clarence Malungani