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 - http://my-domain.com/wp-cron.php?doing_wp_cron into the cron file on the server (http://my-domain.com 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.

2
  • Plugin recommendations are usually not allowed, but in this case, WP Crontrol is excellent and will help you debug and run the cron manually.
    – Q Studio
    Jan 31, 2021 at 23:24
  • get_the_ID() needs to be used in the loop... there is no loop in a cron job... you need to add code to get the post ID(s) you want updated some other way.
    – majick
    Feb 2, 2021 at 3:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.