build_query()WP 2.3.0

Collects a query string from the provided simple/associative array.

The function is needed for convenient creation of URLs with query parameters. The parameter separator is the symbol &.

Unlike the similar PHP function http_build_query(), this function does not encode characters and has no additional parameters. See the example below.

This is a wrapper for the function _http_build_query().

See also the PHP function http_build_query() - generates a URL-encoded query string.

The reverse action can be done using the function wp_parse_str.

Used By: add_query_arg()
1 time — 0.000001 sec (speed of light) | 50000 times — 0.05 sec (speed of light) | PHP 7.2.5, WP 5.0

No Hooks.

Returns

String. URL with query parameters.

Usage

build_query( $data );
$data(array) (required)
Key/value pairs from which to build the query parameters for the URL.

Examples

0

#1 Demo

echo build_query( [ 'one' => 'foo',     'two' => 1     ] ); //> one=foo&two=1
echo build_query( [ 'one' => null,      'two' => 0     ] ); //> two=0
echo build_query( [ 'one' => 'సిరిలిక్',    'two' => ''    ] ); //> one=సిరిలిక్&two=
echo build_query( [ 'one' => 'foo bar', 'two' => false ] ); //> one=foo bar&two=0
echo build_query( [ 'one' => '"<>&+',   'two' => true  ] ); //> one="<>&+&two=1

By comparison, it's the same using a native PHP function:

echo http_build_query( [ 'one' => 'foo',    'two' => 1      ] ); //> one=foo&two=1
echo http_build_query( [ 'one' => null,     'two' => 0      ] ); //> two=0
echo http_build_query( [ 'one' => 'సిరిలిక్',  'two' => ''      ] ); //one=%E0%B0%B8%E0%B0%BF%E0%B0%B0%E0%B0%BF%E0%B0%B2%E0%B0%BF%E0%B0%95%E0%B1%8D&two=
echo http_build_query( [ 'one' => 'foo bar', 'two' => false ] ); //> one=foo+bar&two=0
echo http_build_query( [ 'one' => '"<>&+',   'two' => true  ] ); //> one=%22%3C%3E%26%2B&two=1

As you can see build_query() not urlencode values - it calls _http_build_query() with urlencode = false.

So it is assumed that you had previously urlencoded each individual key and value of your input array! Or it is assumed that you need not encoded values.

0

#2 Example of creating a query

$query = build_query( [
	'action'   => 'info',
	'datatype' => 'json',
] );

$response = wp_remote_get( "https://apisite.com/server/?$query" );

if( 
	! is_wp_error( $response ) 
	&& wp_remote_retrieve_response_code( $response ) === 200 
){
	$json = json_decode( wp_remote_retrieve_body( $response ) );

	print_r( $json );
}

Notes

Changelog

Since 2.3.0 Introduced.

build_query() code WP 6.9.1

function build_query( $data ) {
	return _http_build_query( $data, null, '&', '', false );
}