Expire CPT with WP_CRON

Need change post status for CPT with Cron if post is expired.
My function:

add_action( 'classifieds_auto_expire_hook', 'classifieds_auto_expire_function' );
if (!wp_next_scheduled('classifieds_auto_expire_hook')) {
    wp_schedule_event( time(), 'hourly', 'classifieds_auto_expire_hook' );

function classifieds_auto_expire_function() {
    global $post;

     if(strtotime( $post->post_date ) < strtotime('-10 days')) {
    wp_update_post(array('ID' => $post->ID, 'post_status'   =>  'expired'));


But have problem with ID, when Cron running function not update post status. If I change the $post->ID to real ID, ex. 10, work good.

Have other solution, works perfect:

add_action( 'my_trash_hook', 'my_trash_hook_function' );
if (!wp_next_scheduled('my_trash_hook')) {
    wp_schedule_event( time(), 'hourly', 'my_trash_hook' );

function my_trash_hook_function() {
    global $wpdb;
    $daystogo = "35";
    $sql = $wpdb->prepare("UPDATE wp_posts 
    SET post_status = 'expired' 
    WHERE post_status = 'publish' 
    AND post_type = 'classifieds' 
    AND DATEDIFF(NOW(), post_date) > %d", $daystogo);

But I use another function to send email to user if post is expired based on post_status transitions and if change status via DB request this transition function don’t work (

Read more here: Expire CPT with WP_CRON

Leave a Reply

Your email address will not be published. Required fields are marked *