^ Back to top

WordPress函数:add_query_arg()

You can rebuild the URL and append query variables to the URL query by using this function. There are two ways to use this function; either a single key and value, or an associative array.

Using a single key and value:

add_query_arg( 'key', 'value', 'http://example.com' );

使用关联数组

add_query_arg( array(
    'key1' => 'value1',
    'key2' => 'value2',
), 'http://example.com' );

参数

$key  : (string|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.

用法举例:

(1)、

// 下面代码会输出 '/client/s=word&foo=bar'
echo esc_url( add_query_arg( 'foo', 'bar' ) );
 
// 下面代码会输出 '/client/s=word&foo=bar&baz=tiny'
$arr_params = array( 'foo' => 'bar', 'baz' => 'tiny' );
echo esc_url( add_query_arg( $arr_params ) );

(2)、

/*
 * This would output whatever the URL to post ID 9 is, with 'hello=there'
 * appended with either  or &, depending on what's needed.
 */
echo esc_url( add_query_arg( 'hello', 'there', get_permalink( 9 ) ) );

(3)、

// 下面代码回输出 'http://blog.example.com/2009/04/16/hello=world'
echo esc_url( add_query_arg( 'hello', 'world', 'http://blog.example.com/2009/04/16/' ) );

(4)、

$query = 'http://example.com/linkfoo=bar';
$new_query = add_query_arg( array(
    'foo' => false,
    'baz' => 'qux'
), $query );
print( $new_query );
// http://example.com/linkbaz=qux

(5)、

使用 add_query_arg来获取当前页的完整地址
home_url( add_query_arg( null, null ));

陌陌评论 0

评论前必须登录!

登陆 注册