鹿泽鹿泽  2024-07-15 11:41:18 鹿泽笔记 隐藏边栏  0 

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 );
1、文章版权归作者所有,未经允许请勿转载。
2、本站所有文章,如无特殊说明或标注,均为本站原创发布。任何在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们邮箱:526009505@qq.com进行处理。
3、咨询请联系QQ:526009505