Wordpress 搜索查询修改查询变量

Wordpress search query modify query vars

一位客户要求我在搜索功能中使字符 "S" 和“$”可以互换,即 "Search Query" 和“$earch Query”应该 return 相同的结果。

有没有办法做到这一点?

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

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

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

我确信有办法改进它,我非常乐意实施建议,但这似乎 return 使用两个搜索词的结果,所以它已经足够好了。