Adding query arguments to URLs in WordPress using add_query_arg

The WordPress add_query_arg function is used to build a URL with query parameters added to it. It can be useful for constructing URLs with query strings for use in various scenarios, such as creating custom pagination or filtering options for a website.

By using add_query_arg, developers can easily append or modify query parameters in a URL without having to manually parse and construct the URL string, making it a convenient tool for manipulating URLs dynamically.

Parameters Accepted by WordPress add_query_arg Function

  • $key (string or array, required): Either a query variable key, or an associative array of query variables.
  • $value (string, optional): Either a query variable value, or a URL to act upon.
  • $url (string, optional): A URL to act upon.

The add_query_arg function in WordPress accepts the above parameters to manipulate the URL query string. The function takes in a query variable key, and optionally a value, and a URL to act upon.

When called, the function returns a new URL query string in an unescaped format.

Examples

How to add a single query parameter to a URL using add_query_arg

Use the add_query_arg function to add a single query parameter to a URL.

$url = 'http://example.com/page';
$param_name = 'my_param';
$param_value = '12345';

$new_url = add_query_arg( $param_name, $param_value, $url );

echo $new_url;

How to add multiple query parameters to a URL using add_query_arg

Use the add_query_arg function to add multiple query parameters to a URL.

$url = 'http://example.com/page';
$args = array(
 'param1' => 'value1',
 'param2' => 'value2',
 'param3' => 'value3'
);

$new_url = add_query_arg( $args, $url );

echo $new_url;

How to remove a query parameter from a URL using add_query_arg

Use the add_query_arg function to remove a query parameter from a URL.

$url = 'http://example.com/page?param1=value1&param2=value2';
$param_name = 'param1';

$new_url = remove_query_arg( $param_name, $url );

echo $new_url;

Conclusion

In conclusion, the add_query_arg function is an effective feature for manipulating query parameters in WordPress. It provides a convenient way to add, update, or remove query parameters from a given URL. By using this function, developers can easily modify URLs without having to manually parse and rebuild them. However, it’s important to use this function carefully to avoid potential security risks, such as URL injection attacks. With proper usage, add_query_arg can greatly simplify URL manipulation in WordPress development.

Related WordPress Functions