0

I’m trying to update a boolean custom field based on whether a post has ‘expired’.

A post is considered expired when its publish date exceeds 30 days. To check this, I am retrieving the post publish date using get_the_date() and adding 30 days to it. Then I check whether this new date is greater than or equal to the present date.

However, the if statement used to compare the dates doesn’t seem to get triggered at all. I checked a post which was published today, and the Boolean True / False field is false. I checked a post published a year ago, and it’s still false (expected: true).

Can anyone help me figure out what’s going on? If you have any suggestions as to how I can improve this, please feel free to mention it.

Kind regards.

add_filter('acf/load_field/name=is_listing_expired', 'acf_listing_expiry');
function acf_listing_expiry($field) {

    $start_date_string = get_field('listing_start_date'); //Get the start date value

    $date_format = "Ymd";

    $listing_date = DateTime::createFromFormat($date_format, get_the_date('Ymd', null)); //Convert to a DateTime object
    $modify_amount = "+" . get_field('days_till_expiry') . " days"; //Get the days till expiry value, minimum value is 2

    $new_date = $listing_date->modify($modify_amount); //Get the end date

    $current_date = date($date_format);

    //Check if the date has reached 
    if($new_date <= $current_date) {
        $field['default_value'] = true;
        return $field;
    } else {
        $field['default_value'] = false;
    }
    $field['default_value'] = false;
    return $field;
}
1
  • You're just setting the default value, but if the post has been saved with a value then the default value isn't going to be used. You'd want to change the actual value. Aug 17, 2020 at 14:37

1 Answer 1

0

UPDATE: Turns out I was trying to make a comparison between a DateTime object and the date() function of PHP. When I switched date() to DateTime the comparison was fine.

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.