Retrieve a modified URL (with) query string.
You can rebuild the URL and append a new query variable to the URL query by using this function. You can also retrieve the full URL with query data.
Adding a single key & value or an associative array. Setting a key value to false removes it from the query. Omitting the old query or the uri (second or third parameter) uses the $_SERVER value.
// Parameters as separate arguments
add_query_arg( $param1, $param2, $old_query_or_uri );
// Parameters as array of key => value pairs
add_query_arg( array('key1' => 'value1', ...), $old_query_or_uri );
Assuming we're at the WordPress URL "http://blog.example.com/client/?s=word"... Note the use of esc_url() before outputting the link. This is necessary because this function does not escape urls and if output without escaping would make the page vulnerable to XSS scripting.
// This would output '/client/?s=word&foo=bar' echo esc_url( add_query_arg( 'foo', 'bar' ) ); // 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 ) );
More often than not you'll probably find yourself creating URLs using the following method within the page you're currently on. In these cases you can use the URL you want to affect as the last parameter. The use of esc_url() is not required here, because the value is known to be safe.
// This would output 'http://blog.example.com/2009/04/16/?hello=world' echo esc_url( add_query_arg( 'hello', 'world', 'http://blog.example.com/2009/04/16/' ) );
Since get_permalink() returns a full URL, you could use that when you want to add variables to a post's page.
// This would output whatever the URL to post ID 9 is, with 'hello=there' appended with either ? or &, depending on what's needed echo esc_url( add_query_arg('hello', 'there', get_permalink(9)) );
Removing values and setting via an associative array:
$query = 'http://example.com/link?foo=bar'; $new_query = add_query_arg( array('foo' => false, 'baz' => 'qux'), $query ); // result: http://example.com/link?baz=qux
add_query_arg() is located in