图片待添加
图片待添加

WordPress主题开发教程:只搜索文章标题

2020-02-22 16:01 分类:WordPress主题开发制作教程 阅读(次阅读) 标签:,

WordPress搜索默认是全文的,有些朋友觉得这样既消耗资源又没法及时的展现有效的搜索结果给访客.
之前写了篇:WordPress主题开发教程:搜索结果关键词高亮加粗显示

步骤一:打开自己的模板函数functions.php (在wp-content/themes/下面的你的主题目录)
步骤二:修改functions.php 添加下面的代码

/**
 * WordPress主题开发教程:只搜索文章标题
 * https://www.wpyi.com/sousuo-biaoti.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 );

然后上传覆盖修改的functions.php,再搜索试试,你会发现WordPress搜索内容里面的关键词不再出现在结果中了.


本文地址: https://www.wpyi.com/sousuo-biaoti.html