Query post with meta_query where date is not in future

admin2025-06-03  3

In my args I would like to exclude posts where the datum_event is not in the future. Currently it only displays posts with datum_event values that are in the past, but because older posts don't have any value for datum_event, the old posts don't get shown.

I know how to compare against a single value, but how do I compare against all future dates?

Basically: EXCLUDE posts with datum_event compare future.

$args = array(
    'post_type' => 'agenda',
    'paged' => $paged,
    'meta_query' => array(
        array(
            'key'     => 'datum_event',
            'value'   => date('Ymd'),
            'compare' => '<='
        )
    ),
);

In my args I would like to exclude posts where the datum_event is not in the future. Currently it only displays posts with datum_event values that are in the past, but because older posts don't have any value for datum_event, the old posts don't get shown.

I know how to compare against a single value, but how do I compare against all future dates?

Basically: EXCLUDE posts with datum_event compare future.

$args = array(
    'post_type' => 'agenda',
    'paged' => $paged,
    'meta_query' => array(
        array(
            'key'     => 'datum_event',
            'value'   => date('Ymd'),
            'compare' => '<='
        )
    ),
);
Share Improve this question edited Jan 30, 2019 at 21:48 Ludo asked Jan 30, 2019 at 21:31 LudoLudo 612 silver badges11 bronze badges 4
  • I'm not sure I understood you. You are saying you want to retrieve all posts which have the dateum_event value in the past AND also, at the same time, you want to retrieve posts where the datum_event value is blank (does not exist)? Is that it? – filipecsweb Commented Jan 30, 2019 at 21:41
  • Sorry I forgot to type 'not' :-) I ment I want retrieve all posts which have the datum_event NOT in the future. @filipecsweb – Ludo Commented Jan 30, 2019 at 21:44
  • And the answer below does not fit you? – filipecsweb Commented Jan 30, 2019 at 21:56
  • Let me know if it does not work. – filipecsweb Commented Jan 31, 2019 at 1:17
Add a comment  | 

1 Answer 1

Reset to default 4

You might try adding a second meta_query that would look for anything without the meta key:

$args = array(
    'post_type' => 'agenda',
    'paged' => $paged,
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'     => 'datum_event',
            'value'   => date('Ymd'),
            'compare' => '<='
        ),
        array(
            'key' => 'datum_event',
            'meta_compare' => 'NOT_EXISTS',
            'value' => 'placeholder'
        ),
    ),
);

Note that the value of placeholder is required to the make the not exists work - see https://codex.wordpress/Class_Reference/WP_Query#Custom_Field_Parameters

This is untested code but hopefully it helps!

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748957051a315145.html

最新回复(0)