$loop3 = new WP_Query( array(
'posts_per_page' => 10000,
'post_type' => 'volunteers',
'meta_key' => 'state',
'meta_value' => $stateselect,
'meta_compare' => '=',
'meta_key' => 'volunteer_type',
'meta_value' => 'painter',
'meta_compare' => '=',
) );
Hello. I'm new to PHP and WordPress. I'm having trouble understanding how WP_Query works. I'm trying to get a dataset that looks like this pseudocode:
state=$stateselect AND volunteer_type=painter
The code above seems to be rewriting 'meta_key' and returning results from all 'states', since 'volunteer_type' appears to be overwriting. How do I ...
- Retrieve the results of two different criteria,
- do equivalent of AND between the two different meta_key criterias?
Also, I want to sort the results by a meta_key that is not in the arguments. e.g. There's a field called 'Section' which is alpanumerical. How is sort ASC or DESC done on a field that is not part of the arguments?
Thanks
$loop3 = new WP_Query( array(
'posts_per_page' => 10000,
'post_type' => 'volunteers',
'meta_key' => 'state',
'meta_value' => $stateselect,
'meta_compare' => '=',
'meta_key' => 'volunteer_type',
'meta_value' => 'painter',
'meta_compare' => '=',
) );
Hello. I'm new to PHP and WordPress. I'm having trouble understanding how WP_Query works. I'm trying to get a dataset that looks like this pseudocode:
state=$stateselect AND volunteer_type=painter
The code above seems to be rewriting 'meta_key' and returning results from all 'states', since 'volunteer_type' appears to be overwriting. How do I ...
- Retrieve the results of two different criteria,
- do equivalent of AND between the two different meta_key criterias?
Also, I want to sort the results by a meta_key that is not in the arguments. e.g. There's a field called 'Section' which is alpanumerical. How is sort ASC or DESC done on a field that is not part of the arguments?
Thanks
Share Improve this question asked Feb 23, 2022 at 21:07 menoo320menoo320 12 Answers
Reset to default 0You want to use the newer meta_query
methodology...
You establish a meta_query
and then use arrays for the different conditions you want met, preface them with the relationship relation => 'AND'
or relation => 'OR'
$loop3 = new WP_Query( array(
'posts_per_page' => 10000,
'post_type' => 'volunteers',
'meta_query' => array(
'relation' = 'AND',
array(
'key' => 'state',
'value' => $stateselect,
'compare' => '=',
),
array(
'key' => 'volunteer_type',
'value' => 'painter',
'compare' => '=',
),
),
) );
Codex has a write-up here: https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters
Note
That's a lot, like A LOT, of posts_per_page
.
You should use meta_query:
$loop3 = new WP_Query( array(
'posts_per_page' => 10000,
'post_type' => 'volunteers',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'state',
'value' => $stateselect,
),
array(
'key' => 'volunteer_type',
'value' => 'painter',
),
));