1

I am already filtering some custom posts depending on a querystring in pre_get_posts:

if( $query->is_main_query() ) {
    if( is_post_type_archive( 'events' ) ) {
        if ($_GET['status']) {
            $retrieved_status = $_GET['status'];
            $query->set('meta_key', 'event_status');
            $query->set('meta_value', $retrieved_status);
        }
    }
}

I would then also like to sort by a different custom field, but I can't use something like below because it rewrites the meta_key:

$query->set('orderby', 'meta_value');   
$query->set('meta_key', 'event_date');   
$query->set('order', 'DESC');

How could I structure this to get the desired effect? Thanks!

2 Answers 2

3

Use WP_Query to select any post based on meta key and value. You can also sort posts Ex:

$args = array(
    'post_type'  => 'events',
    'orderby'   => 'meta_value_num', //probably you will need this because the value is date
    'meta_key'  => 'event_date',
    'meta_query' => array(
        'relation'  => 'AND',
        array(
            'key'     => 'event_status',
            'value'   => $retrieved_status, 
            'compare' => '=',
        ),
        array(
            'key' => 'other_key',
            'value'   => 'other_value',
            'type'    => 'numeric', //for example
            'compare' => 'BETWEEN', //for example
        ),
    ),
);
$query = new WP_Query( $args );

See Order & Orderby Parameters & for meta_value_num see Custom Field Parameters

1
  • Thanks, I ended up using meta_query in my pre_get_posts and that has worked.
    – Joe Fawley
    Apr 26, 2017 at 7:28
2

WP_Query has a case for this called a Meta Query where you can pass as many complex arguments as necessary:

$query = new WP_Query array(
    'meta_query'    => array(
        'relation'  => 'AND',       // OR is the default relation parameter, if this is excluded
        array(
            'key'       => 'meta_key_one',
            'value'     => 'meta_value_one',
            'compare'   => '<=',
        ),
        array(
            'key'       => 'meta_key_two',
            'value'     => 'meta_value_two',
            'compare'   => '<=',
        ),
    ),
) );

The above says:

SELECT
    All Posts
    WHERE
    Meta Keys Value One is Less Than or Equal to Passed Value One
    AND
    Meta Keys Value Two is Less Than or Equal to Passed Value Two

Your Answer

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

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