Ive been trying to figure this out for 2 days now and wondering if someone could give some pointers/guidance...
I am getting a list of provinces from a custom field that is stored as an array:
$userprovince = get_user_field ("s2_province_code");
The output using print_r:
Array ( [0] => MB [1] => NU )
Now I'd like to query_posts with a meta_query using that value against the key='province'. I've taken $userprovince and turned it into a multidimensional array using:
for ($i=0; $i< count($userprovince); $i++)
{
$count = count($arrays);
$arrays[$count] = array(
'key' => 'province',
'value' => $userprovince[$i],
'compare' => 'LIKE'
);
}
Which outputs using print_r:
Array ( [0] => Array ( [key] => province [value] => MB [compare] => LIKE ) [1] => Array ( [key] => province [value] => NU [compare] => LIKE ) )
So I've set up my query as follows:
$args = array(
'post_type' => 'clientresource',
'post_status' => 'publish',
'category_name' => 'employment-standards',
'meta_query' => array(
'relation' => 'AND',
$arrays,
'relation' => 'OR',
array(
'key' => 'province',
'value' => 'All',
'compare' => 'LIKE'
)
)); query_posts($args);
My problem - it doesn't work. The correct records are not gathered. However if I manually set the provinces like this:
$args = array(
'post_type' => 'clientresource',
'post_status' => 'publish',
'category_name' => 'employment-standards',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'province',
'value' => 'NB',
'compare' => 'LIKE'
),
array(
'key' => 'province',
'value' => 'NU',
'compare' => 'LIKE'
),
array(
'key' => 'province',
'value' => 'All',
'compare' => 'LIKE')
));query_posts($args);
It works and I get the records expected.
The differences between the 2 meta queries are:
Working:
[meta_query] => Array ( [relation] => OR [0] => Array ( [key] => province [value] => NB [compare] => LIKE ) [1] => Array ( [key] => province [value] => NU [compare] => LIKE ) [2] => Array ( [key] => province [value] => All [compare] => LIKE ) ) )
Not Working:
[meta_query] => Array ( [relation] => OR [0] => Array ( [0] => Array ( [key] => province [value] => MB [compare] => LIKE ) [1] => Array ( [key] => province [value] => NU [compare] => LIKE ) ) [1] => Array ( [key] => province [value] => All [compare] => LIKE ) ) )
What I've been struggling with is how to output my array in meta_query so that it contains the same structure as the working example? I've tried outputting it using var_export but it remains the same. I've also tried using foreach to generate the array in the first place but I still can't get it.
Thank you for reading.