Home › Forums › Front-end Issues › 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.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.