其实WordPress自带搜索功能查找很弱,几十万文章,WordPress搜索居然还搜索了文章内容关键词,难怪卡的不行;
于是想让WordPress自带只搜索文章标题搜索功能,让搜索结果更加精准,同时加快搜索访问体验;
今天分享一下WordPress添加只搜索文章标题的搜索功能方法,可以将下面的代码添加到当前主题functions.php中
代码:
// 只搜索文章标题
function wpse_11826_search_by_title( $search, $wp_query ) {
if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
global $wpdb;
$q = $wp_query->query_vars;
$n = ! empty( $q['exact'] ) ? '' : '%';
$search = array();
foreach ( ( array ) $q['search_terms'] as $term )
$search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );
if ( ! is_user_logged_in() )
$search[] = "$wpdb->posts.post_password = ''";
$search = ' AND ' . implode( ' AND ', $search );
}
return $search;
}
add_filter( 'posts_search', 'wpse_11826_search_by_title', 10, 2 );
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END