一个分享WordPress、Zblog、Emlog、Typecho等主流博客的教程网站!
当前位置:网站首页 > 博客教程 > WordPress教程 > 正文

让 WordPress 只搜索文章的标题

作者:xlnxin发布时间:2021-04-15分类:WordPress教程浏览:535


导读:WordPress默认的搜索功能还真挺弱的,搜索出...

WordPress 默认的搜索功能还真挺弱的,搜索出来的结果很不符合人意,如果你想让它检索出来的结果更加相关,可以限定只搜索文章的标题,将下面的代码添加到主题的 functions.php 文件即可:

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

参考资料:http://wordpress.stackexchange.com/questions/11822/

标签:wordpresshtml主题