最近发现WordPress的搜索功能居然是搜索所有文章内容,让人看了非常不爽,下面我就来分享一下如何让WordPress只搜索文章标题吧!
1、将代码复制到function.php文件中
2、复制以下代码
//---------------------------------------------------------------------------------------只搜索标题--------------------------------------------------------------------------------------------
add_filter( 'posts_search', '_search_by_title', 10, 2 );
function _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;
}
注:代码需放在<?php与?>之间!