如何在WordPress中创建每天发布事件的cron?

时间:2014-06-12 作者:sneha

我想要一个每天发布事件的cron。我想以编程方式设置cron

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\'));
        }
    }
}

1 个回复
SO网友:cybmeta

Wordpress有一个cron API,如果您想使用它,可以使用wp_schedule_event 作用此函数应仅在插件停用时调用,并且应在插件停用时清除计划事件。例如:

 register_activation_hook( __FILE__, \'cyb_activation\' );
 function cyb_activation() {
     wp_schedule_event( time(), \'daily\', \'cyb_daily_event_hook\' );
 }

 add_action( \'cyb_daily_event_hook\', \'cyb_do_this_daily\' );
 function cyb_do_this_daily() {
      // do something every day
 }

 register_deactivation_hook( __FILE__, \'cyb_deactivation\' );
 function cyb_deactivation() {
     wp_clear_scheduled_hook( \'cyb_daily_event_hook\' );
 }
功能cyb_do_this_daily() 每天都会做你想做的事。即您发布的函数。在该函数中,您将生成一个查询post_meta 桌子,我想你应该用WP_Query 对象或get_posts() 而不是直接查询。例如(未测试,只是将查询传递给WP\\u query):

function cyb_do_this_daily(){

     // Get all sold ads
     $args = array(
         \'meta_key\'     = \'cp_ad_sold_date\',
         \'meta_value\'   = \'\',
         \'meta_compare\' = \'!=\'
     );

     $sold_ads = new WP_Query( $args );

     while( $sold_ads->have_posts() ) {

         $sold_ads->next_post()
         $ad = $sold_ads->post;
         $today = time();

         // Get day, month, year
         $date = explode(\'-\',get_post_meta($ad->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->ID, \'post_status\' => \'draft\'));
        }

    }

    wp_reset_postdata();

 }

结束