0

I have a cron task scheduled for every hour and I can see in my monitor that it is running. But, the function below isn't doing what it's supposed to. I'm trying to get any post within 3 different custom post types that have a meta_key of "listing_status" and a meta_value of "active". Then, I compare some custom field data (a date field, "listing_expiration) to the current date and change the listing_status to "expired" if the set date is now in the past. I can't figure out why it's not expiring the posts though...

     //auto-expire active listings every hour (if they are expired)
if ( ! wp_next_scheduled( 'expire_listings' ) ) {
  wp_schedule_event( time(), 'hourly', 'expire_listings' );
}

add_action( 'expire_listings', 'tps_expire_listings' );

//Checks all current listings (that can expire) to see if they are expired, and if so, mark them as such
function tps_expire_listings(){
    $active = array(
        'post_status' => 'publish',
        'post_type'=>array('audition','gig', 'classified'),
        'meta_key'=>'listing_status',
        'meta_value'=>'active',
        'posts_per_page'=> -1,
    );
    $unexpired = get_posts($active);
    foreach ($unexpired as $post) {
        setup_postdata($post);
        if (function_exists('get_field')) {
            $expiresOn = strtotime(get_field('listing_expiration', get_the_ID()));//returns a date formatted in m/d/Y, then timestamp
        }
        $now = strtotime(date('m/d/Y'));
        if ($now >= $expiresOn) {
            update_post_meta(get_the_ID(), 'listing_status', 'expired');
        } else {
            update_post_meta(get_the_ID(), 'listing_status', 'active');
        }
    }
    wp_reset_postdata();
}
1

Figured it out...

I needed to use $post->ID instead of get_the_ID().

  • 1
    The reason why get_the_ID doesn't work is explained on the codex page for setup_postdata, you are using a local version of $post and not the global. – Milo Aug 15 '16 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.