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 );
相关文章:
# 更多WordPress技巧,请关注「WordPress专题」