修改 WordPress 前台搜索文章,只搜索标题

很多朋友在使用 WordPress 时会觉得默认的搜索搜出来的结果不太精准,WordPress 默认会将标题和文章描述中含有关键词的文章都检索出来,这样一来许多标题中不含关键词的文章被搜索出来,用户体验不是很好,解决这个问题的办法就是将默认的搜索改为只搜索标题。这篇文章就来实现这个需求。

而很多网上给出的文章中,都是让在主题的 functions.php 文件中加上这样一段代码

/**
 * 让 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会报出这样一句警告:”Parameter 2 to __search_by_title_only() expected to be a reference, value given in...“,意思是第 2 个参数期待的是一个引用,而实际传过来的是一个值。

所以将 &$wp_query 修改为 $wp_query 即可。

/**
 * 让 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 );
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注