Using WordPress ‘build_query()’ PHP function

The build_query() WordPress PHP function creates a URL query using an associative array or indexed array. It sets the separator to ‘&’ and calls the internal _http_build_query() function. This function also URL-encodes key/value pairs.

Usage

Here’s a straightforward example of using build_query():

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
);
$query = build_query($data);
echo $query;

This will output: key1=value1&key2=value2

Parameters

  • $data (array) – Required parameter. This array contains the key/value pairs that will be URL-encoded.

More information

See WordPress Developer Resources: build_query()
This function calls the _http_build_query() with urlencode set to FALSE. This implies that you should have URL-encoded each key and value in your input array before calling build_query().

If your array contains ‘raw’ data, consider using the native PHP function http_build_query() for proper URL encoding.

Examples

Basic usage

This example builds a simple query string from an array.

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
);
$query = build_query($data);
echo $query; // Outputs: key1=value1&key2=value2

Using Special Characters

This example shows how to build a query with special characters in the array.

$data = array(
    'p%s/n#q?a*e!s p+' => 'percent%slash/number#question?asterisk*exclamate!space plus+end'
);