Get started with 33% off your first certification using code: 33OFFNEW

How to access query parameters in WordPress

2 min read
Published on 28th November 2023

Query parameters, those parts of a URL that come after a question mark (?), are essential in dynamic web development. They're also known as GET variables, named after the HTTP verb. They help pass data between pages and control the behavior of your site based on user interactions. In WordPress, accessing these parameters is a common task and understanding how to do it effectively can greatly enhance your site's functionality. Let's delve into the different ways you can handle query parameters in WordPress.

Understanding Query Parameters

A typical URL with query parameters looks like this:

Here, param1 and param2 are the query parameters, each holding specific values.

Method 1: Using get_query_var()

For custom query vars added via WordPress rewrites or when working with WordPress loops, use get_query_var().

First, ensure your custom query var is registered:

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

Then, retrieve the value:

$my_param = get_query_var('my_param');

Method 2: Accessing Standard Query Parameters

For standard query parameters, use the global $_GET array:

$param1 = isset($_GET['param1']) ? $_GET['param1'] : '';

Method 3: Using the WP_Query Object

If you’re working within a WordPress loop, you can access query parameters directly from the WP_Query object:

global $wp_query;
$param1 = $wp_query->query_vars['param1'] ?? '';

Method 4: Using filter_input()

A more secure way to access query parameters is by using the filter_input() function, which allows you to sanitize the input at the same time:

$param1 = filter_input(INPUT_GET, 'param1', FILTER_SANITIZE_STRING);

Best Practices

  • Validation and Sanitization: Always validate and sanitize query parameters to prevent security vulnerabilities.
  • Check for Existence: Before using a query parameter, check if it exists to avoid undefined index notices.
  • Use WordPress Functions: Whenever possible, use WordPress-specific functions as they often handle many common issues for you.

Use Cases

Query parameters can be used for a variety of purposes like:

  • Filtering Posts: Display posts based on certain criteria, like a category or a date range.
  • Search Results: Handle search queries and display results.
  • Page Navigation: Control pagination of posts or custom post types.