-1

I am trying to detect date if it's greater or not to change post status, in result i am not getting proper way past dates are being greater or sometime future dates its too confusing why dates are not being compared

2020-02-05 (today date) 2020-01-20 (event date)

still it getting detect as greater date for event,

<?php
$loop = new WP_Query( array(
'post_type' => 'events',
'posts_per_page'=> -1,
 )
);
?>

<?php while ( $loop->have_posts() ) : $loop->the_post(); 


                        $today = date("Y-m-d");
                        $date2    = get_field('event_date');




    $event_date = $date2;
    $expire_dt = $today;

    echo '<br>';
    echo $expire_dt;
    echo '<br>';
    echo $event_date;
    echo '<br>';

if ($expire_dt < $event_date) {


                        ?>


<?php 
}else{
echo $today;
    echo $event_date;
    $my_post = array();
    $my_post['ID'] = get_the_ID();
    $my_post['post_status'] = 'draft';

    // Update the post into the database
    wp_update_post( $my_post );

?>

                <?php


}
endwhile; wp_reset_query(); ?>
kamran hassan
  • 166
  • 1
  • 1
  • 13
  • Format the code, please. – Chemaclass Feb 05 '20 at 09:27
  • @B001ᛦ I checked this question and changed my date formats from database, but still i cannot pick right date in my condition – kamran hassan Feb 05 '20 at 09:29
  • Have you verified what `$date2` actually contains? With ACF date fields, the format of the return value can be specified in the field settings, so it must not necessarily be a Y-m-d format. – 04FS Feb 05 '20 at 09:30
  • i customized acf date fields also as mentioned formate, event date i wrote in questions it coming from acf as return and displaying too, – kamran hassan Feb 05 '20 at 09:33
  • Do a `var_dump($date2);`, and report back here with the exact result. – 04FS Feb 05 '20 at 09:43

1 Answers1

2

Wrap the 'event_date' as a DateTime -> new \DateTime(get_field('event_date'))

Try this:

$loop = new WP_Query([
        'post_type' => 'events',
        'posts_per_page' => -1,
    ]
);

while ($loop->have_posts()) {
    $loop->the_post();
    $today = new \DateTime();
    $event_date = new \DateTime(get_field('event_date'));
    // If `get_field()` doesn't work: try `the_field()`...
    // $event_date = new \DateTime(the_field('event_date'));

    if ($today >= $event_date) {
        $my_post = [];
        $my_post['ID'] = get_the_ID();
        $my_post['post_status'] = 'draft';
        wp_update_post($my_post);
    }
}
wp_reset_query();
Chemaclass
  • 1,933
  • 19
  • 24