WordPress博客的确不错,也是我们站长朋友经常选择的程序,可是晓波发现WordPress默认的搜索功能还真挺弱的,用户搜索结果包括文章内容、文章标题与文章标签,这样搜索出来的结果不会很精确,如果你想让它搜索出来的结果更精确、相关,可以限定只搜索文章的标题。下面是晓波给大家分享让WordPress 只搜索文章的标题的方法:
将下面的代码添加到主题的 functions.php 文件即可实现:
//让WordPress只搜索文章的标题
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 );
|