Writing a function for WP Cron to run a SQL command daily

The wp-crontrol plugin allows you to add new cron events as well as new cron schedules. When creating a new event you will need to supply the name of the action hook to use. I guess the easiest way would be to just setup a hook in your themes function.php file:

function update_meta_data($meta_id, $meta_value) {
  global $wpdb;
  $wpdb->update(
    $wpdb->prefix . 'postmeta',
    array('meta_value' => $meta_value),
    array('meta_id' => $meta_id),
    array('%s'),
    array('%d')
  );
}
// Here we are setting up the action hook, notice that we also specify that the
// function takes two arguments.
add_action('cron_update_meta_data', 'update_meta_data', 10, 2);

Then using the wp-crontrol plugin you could create separate events for each of your interval:

  • Hook Name – would be the name of the action hook e.g cron_update_meta_data.
  • Arguments (optional) – would be set to [65138, '4 hours'] for the first event.
  • Next Run – would be set to Tuesday 9am for the first event.
  • Recurrence – set this to run once weekly.

It is also worth noting that wp-cron.php only gets executed when someone visits your website, so depending on how important it is that the cron event is actually run at the specified time you could instead set up a real cron job which in turn will execute wp-cron.php:

0 09 * * TUE curl http://example.com/wp-cron.php?doing_wp_cron > /dev/null 2>&1