wp_delete_post deletes all posts instead of just expired ones

In case anyone else needs the code, this is how I solved it. @pieter-goosen was right, I did need to query the correct posts, but the real trick was matching the date format from the jquery datepicker when running the post query. Check the date formats below, jquery is ‘yy-mm-dd’, and the php equivalent is ‘Y-m-d’.

So the js for the datepicker was:

<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery('.ExDate').datepicker({
            dateFormat: 'yy-mm-dd'
        });
    });
</script>

And the cron function was:

add_action( 'wp', 'delete_expired_adverts_daily' );
function delete_expired_adverts_daily() {
    if ( ! wp_next_scheduled( 'delete_expired_adverts' ) ) {
        wp_schedule_event( time(), 'daily', 'delete_expired_adverts');
    }
}
add_action( 'delete_expired_adverts', 'delete_expired_adverts_callback' );

function delete_expired_adverts_callback() {

    $args = array (
                'post_type'    => 'advert',
                'meta_key'     => 'expires',
                'meta_value'   => date('Y-m-d'),
                'meta_compare' => '<=',
            );

    $query_ads = new WP_Query($args);
    if ($query_ads->have_posts()):
        while($query_ads->have_posts()): $query_ads->the_post();    

            wp_delete_post(get_the_ID(), true);

        endwhile;
    endif;
}

Leave a Comment