WordPress has a cron API and if you want to use it you can do it with wp_schedule_event
function. This function should be called only on ativiation of the plugin and the scheduled event should be cleared on deactivation of the plugin. For example:
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' );
}
The function cyb_do_this_daily()
will perform what you want to do every day. That is, the function you posted. In that function you are building a query to post_meta
table, I think you should use a WP_Query
object or get_posts()
instead of a direct query. For example (not tested, just passed your query to WP_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();
}