最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Setting up a cron job to auto update a custom field

programmeradmin1浏览0评论

I need help to setup a cron job to update a custom field (created with Advanced Custom Field) every 8 hours.

This is the function to define the custom time schedule:

function cron_schedule_eight_hours($schedules) {
    $schedules['eight_hours'] = array(
        'interval' => 8 * HOUR_IN_SECONDS,
        'display' => __('Eight Hours')
    );
    return $schedules;
}

add_filter('cron_schedules', 'cron_schedule_eight_hours');

This is the function to update the custom field by adding a random number to the current value:

function auto_update_custom_field() {
    // get current field value
    $count = (int) get_field('my_numeric_custom_field', get_the_ID());
    // generate a random number
    $random_number = wp_rand(10, 100);
    // sum the current field value and the random number
    $new_value = $count + $randon_number;
    // update the field with the new value
    update_field('my_numeric_custom_field', $new_value, get_the_ID());
}

This is the function to setup the event:

if (!wp_next_scheduled('cron_custom_field')) {
    wp_schedule_event(time(), 'eight_hours', 'cron_custom_field');
} 

add_action('cron_custom_field', 'auto_update_custom_field');

The default WP Cron System starts only when someone visits the site, then I have:

  1. Disabled the WP Cron System by adding into wp-config.php the line define('DISABLE_WP_CRON', true);
  2. Setup a cron job adding the line */15 * * * * wget -q -O - .php?doing_wp_cron into the cron file on the server ( is an example domain).

For some reason the cron job do nothing (obviously for testing purpose I have reduced the custom cron schedule to a few minutes instead of eight hours as defined in the function).

I ask if anyone can help me set up the cron job correctly.

Thanks.

发布评论

评论列表(0)

  1. 暂无评论