get_search_link()
云策文档标注
概述
get_search_link() 函数用于获取搜索结果的固定链接。它根据查询字符串和网站的固定链接设置生成链接,并可通过过滤器进行修改。
关键要点
- 参数 $query 可选,指定查询字符串;若为空,则使用当前搜索查询。
- 返回值为字符串类型的搜索固定链接。
- 函数内部处理 URL 编码和固定链接结构,支持自定义 permalink 设置。
- 通过 apply_filters('search_link', $link, $search) 钩子允许开发者过滤链接。
代码示例
function get_search_link( $query = '' ) {
global $wp_rewrite;
if ( empty( $query ) ) {
$search = get_search_query( false );
} else {
$search = stripslashes( $query );
}
$permastruct = $wp_rewrite->get_search_permastruct();
if ( empty( $permastruct ) ) {
$link = home_url( '?s=' . urlencode( $search ) );
} else {
$search = urlencode( $search );
$search = str_replace( '%2F', '/', $search );
$link = str_replace( '%search%', $search, $permastruct );
$link = home_url( user_trailingslashit( $link, 'search' ) );
}
return apply_filters( 'search_link', $link, $search );
}注意事项
- 确保在调用前正确设置查询字符串或依赖当前查询。
- 注意 URL 编码处理,特别是对于特殊字符如 '/'。
- 使用 apply_filters 钩子可以自定义链接输出。
原文内容
Retrieves the permalink for a search.
Parameters
$querystringoptional-
The query string to use. If empty the current query is used. Default empty.
Source
function get_search_link( $query = '' ) {
global $wp_rewrite;
if ( empty( $query ) ) {
$search = get_search_query( false );
} else {
$search = stripslashes( $query );
}
$permastruct = $wp_rewrite->get_search_permastruct();
if ( empty( $permastruct ) ) {
$link = home_url( '?s=' . urlencode( $search ) );
} else {
$search = urlencode( $search );
$search = str_replace( '%2F', '/', $search ); // %2F(/) is not valid within a URL, send it un-encoded.
$link = str_replace( '%search%', $search, $permastruct );
$link = home_url( user_trailingslashit( $link, 'search' ) );
}
/**
* Filters the search permalink.
*
* @since 3.0.0
*
* @param string $link Search permalink.
* @param string $search The URL-encoded search term.
*/
return apply_filters( 'search_link', $link, $search );
}
Hooks
- apply_filters( ‘search_link’, string $link, string $search )
-
Filters the search permalink.
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |