Support

Account

Home Forums Backend Issues (wp-admin) If Statement is Ignored?

Helping

If Statement is Ignored?

  • Hello.

    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;
    }
  • I have not tested this, but you problem probably stems from the fact that “Ymd” in not a valid input format for DateTime. What I mean is that where you are using get_the_date('Ymd', null)); in this statement $listing_date = DateTime::createFromFormat($date_format, get_the_date('Ymd', null)); is not a valid input value.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.