wordpress搜索功能如何只搜索文章标题

Life is short , play more!
本文来自lihao's Blog,转载请注明。

将如下内容添加到 functions.php 中. 在wordpress 3.4.2 中试验没有问题.

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 );

其次网上提及了另外一种方法,但是并不好用. 大家如果碰到第一种方法不凑效时,可以尝试如下方法.

打开 wp-includes/query.php 此文件,找到如下句,并进行修改.
$search .= “{$searchand}((post_title LIKE ‘{$n}{$term}{$n}’) OR (post_content LIKE ‘{$n}{$term}{$n}’))”;
去掉or 及之后的语句, 并补充上 “; , 保证语法正确.


发表评论

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