Support

Account

Home Forums Front-end Issues WP_Query meta_value oddity

Solving

WP_Query meta_value oddity

  • On this page in the documentation; https://www.advancedcustomfields.com/resources/query-posts-custom-fields/

    it is stated that the $args below will return all posts that have ‘location’ (array) equal to ‘Melbourne’. But I am finding, this will also return posts that have the ‘location’ equal to ‘Melbourne2’ or ‘Little Melbourne’

    Is this correct? And if so, how would I get only those with ‘location’ equal to ‘Melbourne’?

    At the moment I am having to test the results with in_array('location', array('Melbourne') which seems a little clumsy.

    <?php

    // args
    $args = array(
    ‘posts_per_page’ => -1,
    ‘post_type’ => ‘event’,
    ‘meta_query’ => array(
    array(
    ‘key’ => ‘location’,
    ‘value’ => ‘Melbourne’,
    ‘compare’ => ‘LIKE’
    ),
    ),
    );

  • Well right now your code shows a comparison operator of “LIKE” which will indeed perform the behavior you are describing.

    https://wordpress.stackexchange.com/questions/70864/meta-query-compare-operator-explanation

    Replace LIKE with = and you should be good.

  • if only it were that simple…

    “=” returns nothing
    “INCLUDE” returns nothing
    value => array(‘Melbourne’) with compare => “=” (or INCLUDE) returns nothing

  • You need to enclose your value in quotes

    
    value’ => '"Melbourne"',
    

    The values is stored as a serialized array in the database and each value is enclosed in double quotes. To look for specific values you add the quotes to the value to limit the like statement when there are multiple values that may match. The same is true when searching for a specific ID (number) value.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.