实现wordpress搜索结果关键词限制在文章标题

WordPress默认搜索结果是在文章全文匹配,包括文章内容、文章标题与文章标签,但凡文章中包含搜索关键词都会出现在搜索结果中,这样导致搜索出来的结果不够精确,要想提高搜索结果的精确度可以限制搜索关键词只在文章标题匹配,通过下面的代码可以实现。

实现代码:

把下面的代码添加到当前主题的functions.php文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function __search_by_title_only($search, &$wp_query) {
    if (empty($search)) return $search; // skip processing - no search term in query
    $q = &$wp_query - >query_vars;
    // wp-includes/query.php line 2128 (version 3.1)
    $n = !empty($q['exact']) ? '': '%';
    $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 ';
    }
    $term = esc_sql(like_escape($q['s']));
    if (empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s']) $search. = " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
    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', 10, 2);

保存即可

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Grow your business fast with

Suku