增强 wordpress搜索功能

PHPABC WordPress 926 次浏览 , 没有评论

1.增加WordPress搜索的关联性

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";
}

只搜索文章
只搜索文章的标题,将下面的代码添加到主题的 functions.php 文件即可:

/**
* 让 WordPress 只搜索文章的标题
*/
function __search_by_title_only( $search, &$wp_query )
{
global $wpdb;
if ( emptyempty( $search ) )
return $search; // skip processing – no search term in query
$q = $wp_query->query_vars;
$n = ! emptyempty( $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 ( ! emptyempty( $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 );

选择分类搜索文章:

将默认的searchform.php修改为以下代码:

<form id=”searchform” name=”searchform” method=”get” action=”<?php bloginfo(‘home’); ?>/” >
<ul>
<li>
<p>
<?php $select = wp_dropdown_categories(class=search_select&show_option_all=全站搜索& amp;orderby=name&hierarchical=0&selected=-1&depth=1);?>
</p>
</li>
<li>
<input type=”text” name=”s” id=”s” maxlength=”34″ value=””/>
</li>
<li>
<input type=”image” value=”” src=”<?php bloginfo(‘template_url’); ?>/img/search.gif”/>
</li>
</ul>
</form>

发表评论

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Go