欢迎光临
我们一直在努力

让 WordPress 只搜索文章的标题

建站超值云服务器,限时71元/月

WordPress 默认的搜索功能还真挺弱的,搜索出来的结果很不符合人意,如果你想让它检索出来的结果更加相关,可以限定只搜索文章的标题,将下面的代码添加到主题的 functions.php 文件即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * 让 WordPress 只搜索文章的标题
 * https://www.wpdaxue.com/search-by-title-only.html
 */
function __search_by_title_only( $search, &$wp_query )
{
	global $wpdb;
 
	if ( empty( $search ) )
        return $search; // skip processing - no search term in query
 
    $q = $wp_query->query_vars;    
    $n = ! empty( $q['exact'] ) ? '' : '%';
 
    $search =
    $searchand = '';
 
    foreach ( (array) $q['search_terms'] as $term ) {
    	$term = esc_sql( like_escape( $term ) );
    	$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
    	$searchand = ' AND ';
    }
 
    if ( ! empty( $search ) ) {
    	$search = " AND ({$search}) ";
    	if ( ! is_user_logged_in() )
    		$search .= " AND ($wpdb->posts.post_password = '') ";
    }
 
    return $search;
}
add_filter( 'posts_search', '__search_by_title_only', 500, 2 );

/** * 让 WordPress 只搜索文章的标题 * https://www.wpdaxue.com/search-by-title-only.html */ function __search_by_title_only( $search, &$wp_query ) { global $wpdb; if ( empty( $search ) ) return $search; // skip processing – no search term in query $q = $wp_query->query_vars; $n = ! empty( $q[‘exact’] ) ? ” : ‘%’; $search = $searchand = ”; foreach ( (array) $q[‘search_terms’] as $term ) { $term = esc_sql( like_escape( $term ) ); $search .= “{$searchand}($wpdb->posts.post_title LIKE ‘{$n}{$term}{$n}’)”; $searchand = ‘ AND ‘; } if ( ! empty( $search ) ) { $search = ” AND ({$search}) “; if ( ! is_user_logged_in() ) $search .= ” AND ($wpdb->posts.post_password = ”) “; } return $search; } add_filter( ‘posts_search’, ‘__search_by_title_only’, 500, 2 );

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 让 WordPress 只搜索文章的标题
分享到: 更多 (0)