WordPress本身的搜索结果是按照发布时间排序的,这样的搜索结果的相关性并不强,应该让搜索结果按照内容相关性排序,而不是按照时间或者 ID,所以我们可以在当前主题的 functions.php
添加如下代码来增强 WordPress 搜索的相关性:
//提高搜索结果相关性
if(is_search()){
add_filter('posts_orderby_request', 'search_orderby_filter');
}
function search_orderby_filter($orderby = ''){
global $wpdb;
$keyword = $wpdb->prepare($_REQUEST['s']);
return "((CASE WHEN {$wpdb->posts}.post_title LIKE '%{$keyword}%' THEN 2 ELSE 0 END) + (CASE WHEN {$wpdb->posts}.post_content LIKE '%{$keyword}%' THEN 1 ELSE 0 END)) DESC,
{$wpdb->posts}.post_modified DESC, {$wpdb->posts}.ID ASC";
} |
//提高搜索结果相关性
if(is_search()){
add_filter('posts_orderby_request', 'search_orderby_filter');
}
function search_orderby_filter($orderby = ''){
global $wpdb;
$keyword = $wpdb->prepare($_REQUEST['s']);
return "((CASE WHEN {$wpdb->posts}.post_title LIKE '%{$keyword}%' THEN 2 ELSE 0 END) + (CASE WHEN {$wpdb->posts}.post_content LIKE '%{$keyword}%' THEN 1 ELSE 0 END)) DESC,
{$wpdb->posts}.post_modified DESC, {$wpdb->posts}.ID ASC";
}
上面的排序方法很简单:当文章标题含有关键字的时候给予权重值 2,内容里含有关键字的时候给予权重值 1,把两个权重值相加以后降序排列。然后才用文章修改时间和ID降序作为候补排序方法。这样一来,搜索出来的结果就更加准确了。
来源:
https://www.wpdaxue.com/improve-wordpress-search-results.html
微信公众号
手机浏览(小程序)
Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(): Failed to enable crypto in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32834.jpg): failed to open stream: operation failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57