让WordPress只搜索文章的标题

Title Search
Title Search

Wordpress搜索质量不是很好,限定只搜索文章的标题,有时候结果反而会好一点,将下面的代码添加到主题的 functions.php 文件即可:

/**
* 让 WordPress 只搜索文章的标题
*/
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 );

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注