build_query()
converts an array into a string to be used in an URL. You can pass an array or an object:
$test1 = array (
'foo' => 'bar',
'hello' => 'world'
);
$query1 = build_query( $test1 );
print "<pre>$query1</pre>"; // foo=bar&hello=world
$test2 = array (
'foo' => 'bar',
'hello' => 'world',
'one' => array( 1, 2 ),
'two' => array(
'a' => 3,
'b' => 4
)
);
$query2 = build_query( $test2 );
print "<pre>$query2</pre>"; // foo=bar&hello=world&deep%5Ba%5D=1&deep%5Bb%5D=2
$test3 = new stdClass;
$test3->foo = 'bar';
$test3->arr = array( 5, 6, 'red' );
$query3 = build_query( $test3 );
print "<pre>$query3</pre>"; // foo=bar&arr%5B0%5D=5&arr%5B1%5D=6&arr%5B2%5D=red
To get the current URL you can use something like this:
$url = set_url_scheme(
'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
);
Now you could use build_query()
to append your custom array values to the URL, but you can make that easier with add_query_arg()
:
$custom = array( 'name' => 'me' );
$url = add_query_arg( $custom, $url );
add_query_arg()
will look for existing parameters in the URL and make sure they don’t get lost or interfere with the $custom
values. If there are duplicate entries in both, $custom
will overwrite existing parameters.
build_query()
is used in add_query_arg()
too, but for no obvious reasons you cannot pass an object to add_query_arg()
like you can use it in build_query()
. Objects are dropped silently.