给WordPress 自带的搜索功能添加过滤只搜索文章的标题

如果想让 WordPress 自带的搜索功能只搜索文章标题,让搜索结果更加精确(其实WordPress 自带的搜索功能本来模糊查找就很弱),可以将下面的代码添加到当前主题functions.php中:
用过滤器:posts_search 就可以了。

// 只搜索文章标题
function wpdocs_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($wpdb->esc_like($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', 'wpdocs_search_by_title_only', 500, 2);

你可能感兴趣的:(ajax,正则表达式,chrome,safari,css3,ecmascript,bootstrap)