wp_query not searching with apostrophe

I'm trying to search WP_Query for the data containing the phrase "Dalton's Law" in meta_query. This is an AJAX search, and here's what I"m doing:

//in this case $_POST['query'] is the phrase "Dalton's Law"

$query = apply_filters( 'get_search_query', $_POST['query'] );
$query = esc_html( $query );

$guide_meta_args   = array(
    'post_type'           = array( 'guide' ),
    'post_status'         = 'publish',
    'ignore_sticky_posts' = true,
    'posts_per_page'      = 4,
    'meta_query' = array(
        array(
            'key'     = 'guide_raw_data',
            'value'   = $query,
            'compare' = 'LIKE',
        ),
    )

);

I will have success for typing up to "Dalton", but as soon as I get to the apostrophe, the search fails. When I get code back from the my javascript, i can console.log the search string and it is dalton\#039;s So it appears that the encoding is working properly, but WP_Query doesn't like the apostrophe... does anyone have suggestions? Thanks so much!

Topic htmlspecialchars-decode meta-query ajax escaping wp-query Wordpress

Category Web


Try using sanitize_text_field instead of esc_html

wp> $search_query = "Dalton's Law <br/>";
string(18) "Dalton's Law <br/>"
wp> $query = apply_filters( 'get_search_query', $search_query );
string(18) "Dalton's Law <br/>"
wp> $esc_html = esc_html( $query );
string(29) "Dalton&#039;s Law &lt;br/&gt;"
wp> $sanitized = sanitize_text_field( $query );
string(12) "Dalton's Law"

esc_html should be used to escape output before it goes into HTML.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.