Asfandyar Khan
Asfandyar Khan

Reputation: 1738

Using Soundex in wordpress or woocommerce default search Query?

Trying to use soundex() function in search so I can get the results whose value sounds like same.

I have created 6 posts.

  1. Hur
  2. Hur The Beautiful
  3. Hoor
  4. Hoor the Brand
  5. Hwr
  6. Hwr the beautiful

All above 6 posts contains (Hur, Hoor, Hwr) and sounds same "E600". How Can I overwrite the wordpress default search ? If I search for "Hur", it should return all 6 posts.

I have tried in Woocommerce as well, but it doesn't work. I have used multiple methods like "pre_get_posts" or "post_where" no of them worked properly.

add_filter('pre_get_posts', 'custom_post_search', 10, 2);
function custom_post_search($query)
{
    global $wpdb;

    if (is_search() || !is_admin()) {

       $searchTerm = $query->get('s');
        $searchTerm = "bad";
      //  $query = "";
      // $query = "SELECT * FROM {$wpdb->posts} WHERE soundex(post_title) LIKE soundex($searchTerm) and post_type = 'post'";
      //  $query->set(soundex('post_name'), soundex($searchTerm));
      //    $query->set('post_name', soundex($searchTerm));
    }
    return $query;
}

I have done many changes in above code, But none of them worked. I have also used where filter.

add_filter('posts_where', 'attaching_custom_filter_where', 10, 2);
function attaching_custom_filter_where($where = "", \WP_Query $q)
{
global $wpdb;
$searchTerm = $q->get('s');

//$where = ""; // If I uncomment this to overwrite the query, it doesn't work.
$where .= ' OR soundex (' . $wpdb->posts . '.post_title) LIKE \'%' . soundex($searchTerm) . '%\'';
// Using OR will run default Wordpress Query along with our query, It shows other records too.

return $where;
}

Upvotes: 0

Views: 242

Answers (1)

Andrew Schultz
Andrew Schultz

Reputation: 4243

I used the posts_search filter to achieve something similar for an AJAX search I was working on.

add_filter('posts_search', 'soundex_search', 20, 2);

function soundex_search($search, $wp_query)
{
    global $wpdb;

    $search_term = $wp_query->get('s');

    if (!is_admin() && $wp_query->is_search()) {
        $search = " AND ((($wpdb->posts.post_title LIKE '%$search_term%') OR 
        ($wpdb->posts.post_excerpt LIKE '%$search_term%') OR 
        ($wpdb->posts.post_content LIKE '%$search_term%')  OR (soundex (w0rd_posts.post_title) = soundex('$search_term'))
        ))";
    }

    return $search;
}

I overwrote the default where clause that gets passed via the first parameter $search with my own custom one.

Upvotes: 0

Related Questions