Using WordPress ‘add_query_arg()’ PHP function

The add_query_arg() WordPress PHP function allows you to rebuild the URL and append query variables to the URL query. This function can be used in two ways: either by providing a single key and value, or by providing an associative array. If the URL is omitted from either use, the current URL will be used instead, courtesy of the value of $_SERVER[‘REQUEST_URI’].

Usage

Here’s a basic usage scenario of how to use the function:

// Using a single key and value
add_query_arg('key', 'value', 'http://example.com');

// Using an associative array
add_query_arg(array('key1' => 'value1', 'key2' => 'value2', ), 'http://example.com');

Parameters

  • $key (string|array) (Required): This can be either a query variable key, or an associative array of query variables.
  • $value (string) (Optional): This can be either a query variable value, or a URL to act upon.
  • $url (string) (Optional): This is a URL to act upon.

More Information

See WordPress Developer Resources: add_query_arg()

Note: The return value of add_query_arg() is not escaped by default. Always escape output with esc_url() or similar functions to prevent vulnerability to cross-site scripting (XSS) attacks.

Examples

Add single query arg to current URL

This example appends ‘foo’ and ‘bar’ to the current URL.

// This would output '/client/?s=word&foo=bar'
echo esc_url( add_query_arg( 'foo', 'bar' ) );

Add multiple query args to current URL

This example appends ‘foo’ => ‘bar’ and ‘baz’ => ‘tiny’ to the current URL.

// This would output '/client/?s=word&foo=bar&baz=tiny'
$arr_params = array('foo' => 'bar', 'baz' => 'tiny');
echo esc_url( add_query_arg( $arr_params ) );

Add query arg to a specific post URL

This example appends ‘hello’ => ‘there’ to the URL of post with ID 9.

// This would output the URL to post ID 9, with 'hello=there' appended
echo esc_url( add_query_arg( 'hello', 'there', get_permalink(9) ) );

Remove existing query arg and add new one

This example removes ‘foo’ query arg and adds ‘baz’ => ‘qux’ to the given URL.

$query = 'http://example.com/link?foo=bar';
$new_query = add_query_arg( array( 'foo' => false, 'baz' => 'qux' ), $query );
print( $new_query ); // http://example.com/link?baz=qux

Get current URL

This example retrieves the current URL.

// This would return the current URL
$current_url = add_query_arg(array());
echo $current_url;