0

I have a WordPress website with a custom product post type. I'm experiencing an issue with the search functionality where it doesn't consider variations of the apostrophe character ('). For example, when searching for "D’Alba", it only returns results for "D’Alba" and vice versa not getting value of D'Abla.

I've tried several approaches to address this issue, but none of them have been successful. Here's the current code I'm using in my search function:

    function include_character_variations_in_product_search($search, $query)
{
    global $wpdb;

    if (is_admin() && $query->is_main_query() && $query->get('post_type') === 'product' && isset($query->query_vars['s'])) {
        $search_terms = $query->query_vars['s'];
        echo $search_terms;
        $search_terms = str_replace(array("’", "'"), array("'", "’"), $search_terms);
        if (!empty($search_terms)) {
            $search = "AND (
                ($wpdb->posts.post_title LIKE '%" . esc_sql($search_terms) . "%')
                OR ($wpdb->posts.post_content LIKE '%" . esc_sql($search_terms) . "%')
                OR ($wpdb->posts.post_excerpt LIKE '%" . esc_sql($search_terms) . "%')
            )";
        }
    }

    return $search;
}

add_filter('posts_search', 'include_character_variations_in_product_search', 10, 2);

I've also tried replacing the apostrophe variations using str_replace, but it didn't yield the expected results. Additionally, I attempted to modify the SQL query using the get_search_sql filter, but it resulted in a 500 error.

I need the search functionality to consider both "D'Alba" and "D’Alba" not as separate search terms and return the relevant products. Can anyone provide guidance on how to handle apostrophe variations in the WordPress search for a custom product post type?

Any help or suggestions would be greatly appreciated. Thank you!

1
  • Sorry if this sounded silly, but, can't you just separately search for D’Alba and then D'Alba? Because if you want WordPress to search for both keywords at the same time, then you would want to use two LIKE clauses - post_title LIKE '%D’Alba%' OR post_title LIKE '%D\'Alba%'. (and the same goes with the other fields - post_content and post_excerpt) But your code isn't doing that, and your str_replace() code is also not working correctly.
    – Sally CJ
    Jul 4 at 6:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.