WordPress | How to retrieve query variables in plugins

|
| By Webner

Suppose the URL contains query string for example www.mywebsite.com/sme_page?q=12
then the value of query variable can be retrieved in PHP using the get method such as:

<?php
echo $_GET['q'];  
?>

While creating a plugin for WordPress, to retrieve a value of query variables, filter for query variables is designed, and variables whose value is to be retrieved are added to the filter function in the following manner:

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

After designing the filter, query variable value can be obtained with the WordPress function get_query_var(‘q’).

Suppose website page has url containing 2 or more query variables:

www.mywebsite.com/some_page?id=12&body_type=2dr car

Below is the example showing how to retrieve values for query variables from URL:

function add_query_vars_filter($vars) {
$vars[] = "id";
$vars[] = "body_type";
return $vars;
}
add_filter('query_vars', 'add_query_vars_filter');
function some_page_function() {
echo " < pre > ID = ".get_query_var('id')."
Type ".get_query_var('body_type');
}

//Output on a webpage:
1

Leave a Reply

Your email address will not be published. Required fields are marked *