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(
            '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\'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!

  • Keep in mind that querying via post meta is very expensive, you'll also want to be sure it's saved HTML encoded too – Tom J Nowell Feb 16 '18 at 0:19

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.