remove_query_arg()
云策文档标注
概述
remove_query_arg() 函数用于从查询字符串中移除一个或多个参数,返回修改后的 URL 字符串。开发者需注意其返回值默认未转义,输出时应使用 esc_url() 进行后期转义以防止 XSS 攻击。
关键要点
- 函数接受两个参数:$key(必需,字符串或字符串数组,指定要移除的查询键)和 $query(可选,默认为 false,表示使用当前 URL)。
- 返回值是新的 URL 查询字符串,可直接用于链接构建。
- 安全提示:输出前必须使用 esc_url() 转义返回值,确保安全性。
- 支持批量移除参数,通过传递数组实现。
代码示例
// 移除单个参数并输出转义后的 URL
echo esc_url( remove_query_arg( 'details' ) );
// 移除多个参数
$arr_params = array( 'details', 'type', 'date' );
echo esc_url( remove_query_arg( $arr_params ) );
// 指定目标 URL 进行参数移除
echo esc_url( remove_query_arg( 'details', 'http://www.example.com/2014/03/11/?details=value1' ) );注意事项
函数内部通过 add_query_arg() 实现参数移除,开发者应避免直接操作查询字符串,优先使用此函数以确保兼容性和安全性。相关函数包括 add_query_arg(),用于添加查询参数。
原文内容
Removes an item or items from a query string.
Description
Important: The return value of remove_query_arg() is not escaped by default. Output should be late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting (XSS) attacks.
Parameters
$keystring|string[]required-
Query key or keys to remove.
$queryfalse|stringoptional-
When false uses the current URL.
Default:
false
Source
function remove_query_arg( $key, $query = false ) {
if ( is_array( $key ) ) { // Removing multiple keys.
foreach ( $key as $k ) {
$query = add_query_arg( $k, false, $query );
}
return $query;
}
return add_query_arg( $key, false, $query );
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 3 content
Codex
Assuming we’re at the WordPress URL “http://www.example.com/client/?details=value1&type;=value2&date;=value3″…
Note the use of
esc_url()before outputting the link.// This would output '/client/?type=value2&date;=value3' echo esc_url( remove_query_arg( 'details' ) ); // This would output '/client/' $arr_params = array( 'details', 'type', 'date'); echo esc_url( remove_query_arg( $arr_params ) );Skip to note 4 content
Codex
When you want to manipulate a URL that is not of the page your script is in, add the targeted URL in the second parameter as below. The use of
esc_url()is not required here (though encouraged), because the value is known to be safe:// This would output 'http://www.example.com/2014/03/11/' echo esc_url( remove_query_arg( 'details', 'http://www.example.com/2014/03/11/?details=value1' ) ); // This would output 'http://www.example.com/2014/03/11/?type=value2&date;=value3' echo esc_url( remove_query_arg( 'details', 'http://www.example.com/2014/03/11/?details=value1&type;=value2&date;=value3' ) ); // This would output 'http://www.example.com/2014/03/11/' $arr_params = array( 'details', 'type', 'date'); echo esc_url( remove_query_arg( $arr_params, 'http://www.example.com/2014/03/11/?details=value1&type;=value2&date;=value3' ) );