Only query posts that are newer than 28 days

Hi. Im trying to use a Meta Query to get posts that are younger than 28 days, but it’s not behaving as it should.

META KEY
post_date

META VALUE
{echo:calculate_28_days_before({current_date:d-m-Y})}

COMPARE
Greater than or equal

TYPE
Date

Now the script i use to calculated the comparison date (28 days before) is this:

<?php 

function calculate_28_days_before($date) {

    $datetime = DateTime::createFromFormat('d-m-Y', $date);

    if ($datetime === false) {
        // Handle the error appropriately
        return 'Invalid date format';
    }

    // Subtract 28 days from the date
    $datetime->modify('-28 days');

    return $datetime->format('d-m-Y');
}

Now the output of both post_date and my function are exactly the same format - d-m-Y.

I know this query should return posts, but it doesn’t. Any good ideas?

query

Hi Sridhar

Thanks for the tutorial - i don’t love the solution of having to target the ID of the loop in the PHP. Makes it more of a hassle when I have lots of loops to create and maintain. Do you think it’s the only way? :smile:

Not sure you are looking at the updated tutorial. We don’t need to specify the ID with the query PHP editor - when using query loops.

1 Like

My bad - you are right, this is fantastic :slight_smile:

While a solution has been found, I’m still curious as to why my original solution did not work.

As far as I know, there is no post meta called post_date.

Maybe not - but there is a standard wordpress dynamic data tag called post_date

Sure. But that can’t be used as the value of Meta key control since it is not a meta key.

Okay, then thats probably it. Although I also tried to use a custom field using ACF which stored the date instead of post_date, having the same problem. But, your solution works, so thank you - i’ll move on :smile:

Unless I’m mistaken, it’s not possible to pass data to a function called with the echo dynamic data tag. I was trying to do this myself for another purpose and ran into an issue as well.

To clarify, you mean in meta query right? Because I can successfully pass data to an echo function outside of meta query just fine - in a code module / text module for instance.

We can, it’s just these arguments can’t be custom functions themselves.

{echo:function(text)} works.

I believe it is possible to pass in dynamic data tags as arguments though.

2 Likes