Basically I wrote a function that lets me change the post status to draft depending of a field in the postmeta table:

/**
 * Remove ads if they have been sold for over 5 days
 */
function cp_remove_sold_ads(){

    global $wpdb;
    // Get all sold ads
    $sold_ads = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "postmeta WHERE `meta_key` = 'cp_ad_sold_date' AND `meta_value` <> ''");

    foreach ($sold_ads as $ad) {
        $today = time();

        // Get day, month, year
        $date = explode('-',get_post_meta($ad->post_id, 'cp_ad_sold_date', true));

        $sold_date = mktime(null, null, null, $date[1], $date[2], $date[0]);
        $date_diff = $today - $sold_date;

        // Get the days difference
        $sold_day_diff = floor($date_diff / (60*60*24));

        if ($sold_day_diff >= 5) {
            wp_update_post(array('ID' => $ad->post_id, 'post_status' => 'draft'));
        }
    }
}

This works fine, and if I add the function to the init action it does what its supposed to:

add_action( 'init' , 'cp_remove_sold_ads' );

However I'd like to make this action execute daily instead, I've been looking around and found that WP uses wp_schedule_event to hanlde cron jobs, but I have no idea how to use it, does anyone know what do I have to add to handle it?

Thanks in advance!

link|improve this question

feedback

1 Answer

up vote 2 down vote accepted

Just look at the examples in the WordPress Codex for:

  1. wp_schedule_event
  2. wp_schedule_single_event
link|improve this answer
Yes, especially the example that uses register_activation_hook and register_deactivation_hook. This ensures you only schedule one recurring job. – Andy Mar 31 '11 at 19:30
@Andy: Thanks for the addition. In themes (functions.php) the register_ hooks aren't present. There we could use if(!wp_next_scheduled('my_event')) { wp_schedule_event($args); }. – rofflox Mar 31 '11 at 19:36
Thanks a lot, indeed @Roman that's what I added to my theme and it worked just fine. – javiervd Mar 31 '11 at 20:12
feedback

Your Answer

 
or
required, but never shown

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