0

My goal is to remove posts from my wordpress based home/category pages after they are no longer topical.

I have an 'expire_date' custom field for each post where I enter the date I want them to drop off.

Then (with help from Sally CJ), I use wp_query to filter through the posts and filter out the expired posts:

$query_args['meta_query'] = array(
    array( // clause/query 1
        'key'     => 'expire_date',
        'value'   => date("Y-m-d"),
        'type'    => 'DATE',
        'compare' => '>=',
    )
);

That works great for the posts that have an entry in the 'expire_date' field... however, many posts don't - and apparently they are being filtered out to. They are not included in the results.

So how do I include those posts that don't have an entry?

I read through the wp_query doc and tried this - but the results is that none of the posts are displayed -

$query_args['meta_query'] = array(
    array( // clause/query 1
        'key'     => 'expire_date',
        'value'   => date("Y-m-d"),
        'type'    => 'DATE',
        'compare' => '>=',
    ),
            
    array(
        'relation' => 'OR',
        array(
            'key'     => 'expire_date',
            'compare' => 'NOT EXISTS'
        )
    )
            
);

clearly I am in over my head :) Any help appreciated!

Chris

3
  • 1
    The relation should be in the same level as the two arrays/clauses in your meta_query array, i.e. 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'expire_date', ... ), array( 'key' => 'expire_date', ... ) ) :)
    – Sally CJ
    Aug 12, 2022 at 1:36
  • 1
    Yea! That's perfect, working completely now, so excited - I've been stuck trying to figure this out for a week. Thank you so much for your help Sally CJ!
    – Chris
    Aug 12, 2022 at 17:44
  • 1
    Sally CJ, would you like to copy your comment over as an answer so I can mark it as such and give you credit?
    – Chris
    Aug 12, 2022 at 17:48

1 Answer 1

1

how do I include those posts that don't have an entry?

You can include those posts (which do not have the expire_date field/meta) by adding a second clause with 'compare' => 'NOT EXISTS', and then set the relation to OR:

$query_args['meta_query'] = array(
    // the relation between the root clauses/queries; defaults to AND
    'relation' => 'OR',

    array( // root clause/query 1
        'key'     => 'expire_date',
        'value'   => date("Y-m-d"),
        'type'    => 'DATE',
        'compare' => '>=',
    ),

    array( // root clause/query 2
        'key'     => 'expire_date',
        'compare' => 'NOT EXISTS',
    ),
);

So actually, you just needed to remove lines 15 and 9 in the code in question.

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.