build_query()
Build URL query based on an associative and, or indexed array.
This is a convenient function for easily building url queries. It sets the separator to '&' and uses _http_build_query() function.
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.
Return
String
. URL-encoded string.
Usage
build_query( $data );
- $data(array) (required)
- URL-encode key/value pairs.
Examples
#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.
#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
- See: _http_build_query() Used to build the query
Changelog
Since 2.3.0 | Introduced. |
build_query() build query code WP 6.7.2
function build_query( $data ) { return _http_build_query( $data, null, '&', '', false ); }