0
$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

2 Answers 2

0

You 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.

0

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',
        ),
)); 
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Feb 27, 2022 at 5:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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