How to change users smart quotes to dumb quotes in search bar?

I have a problem where smart quotes (curly) will not return any search results but dumb quotes (straight) will give what I expect.

I would like to give all users the same experience so I need to allow smart or dumb quotes to be entered in the search bar but would ultimately return the product with the dumb quotes as it is currently in the DB

I need to do this for both double and singles quotes.

1 Answer
1

Try this. It’s a function that will filter the search query and replace any smart quotes with their “dumb” equivalent.

<?php

/**
 * Filter smart quotes out of a search query.
 * Replace them with "dumb" quotes.
 *
 * @param WP_Query $query Instance of WP_Query.
 */
function filter_search_smart_quotes( $query ) {
    if ( $query->is_search() ) {
        $search = $query->get( 's' );

        $smart_quotes = array(
            chr( 145 ),
            chr( 146 ),
            chr( 147 ),
            chr( 148 ),
            chr( 151 ),
        );

        $dumb_quotes = array(
            "'",
            "'",
            '"',
            '"',
            '-',
        );

        $search = str_replace( $smart_quotes, $dumb_quotes, $search );

        $query->set( 's', $search );
    }
}
add_action( 'pre_get_posts', 'filter_search_smart_quotes' );

Leave a Comment