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 //让WordPress只搜索文章的标题
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'] ) ? '' : '{5cc1b29162d549a8071384de182cc9fc6e6a0fd85e7907f22fd9e18cff4269c3}';
$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 );原文链接:https://xiaohost.com/1436.html,转载请注明出处。
评论0