Wordpress搜索查询修改查询变量

时间:2015-01-31 10:19:28

标签: wordpress search

客户要求我在搜索功能中使字符“S”和“$”可互换,即“搜索查询”和“$ earch查询”应返回相同的结果。

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:0)

在WP查询数据库之前更改它:

$the_replacements = array(
    '$' => 'S',
);
function modify_search_vars($search_vars) {
    global $the_replacements;
    if (!empty($search_vars['s']) && !empty($the_replacements[$search_vars['s']])) {
        $search_vars['s'] = $the_replacements[$search_vars['s']];
    }
    return $search_vars;
}
add_filter('request', 'modify_search_vars', 99);

答案 1 :(得分:0)

这似乎运作得很好我猜...

add_action('pre_get_posts', 'modified_search');
function modified_search($query){
    global $wp_query;
    if($query->is_search){
        global $wpdb;
        $original_query = get_search_query();
        $modified_query = preg_replace("/(s|S)/", "$", $original_query);
        $new_query = "
            SELECT $wpdb->posts.ID
            FROM $wpdb->posts
            WHERE $wpdb->posts.post_status = 'publish'
            AND (($wpdb->posts.post_title LIKE '%$original_query%') OR ($wpdb->posts.post_content LIKE '%$original_query%') OR ($wpdb->posts.post_title LIKE '%$modified_query%') OR ($wpdb->posts.post_content LIKE '%$modified_query%'))
            ORDER BY $wpdb->posts.post_date DESC
            LIMIT 0, 10
        ";
        $results = $wpdb->get_results($new_query);
        $post_ids = array();
        foreach ($results as $post_id){
            $post_ids[] = $post_id->ID;
        }
        $query->set('post__in', $post_ids);
    }
}

我确信有很多方法可以改进这一点,而且我很乐意实施建议,但这似乎会使用两个搜索字词返回结果,所以它已经足够了。