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

I usually use the events manager in PHP MyAdmin to set up scheduled events but since migrating to WP Engine they do not allow it and I must write a function to use WP Cron instead. What should this look like written as a WP function?

I have the SQL command:

UPDATE wp_postmeta SET meta_value = '4 hours' WHERE wp_postmeta.meta_id = 65138;

I need to run it be recurring, for example

Every Monday at 9am

UPDATE wp_postmeta SET meta_value = '4 hours' WHERE wp_postmeta.meta_id = 65138;

On Tuesday at 9am

UPDATE wp_postmeta SET meta_value = '8 hours' WHERE wp_postmeta.meta_id = 65138;

On Wednesday at 9am

UPDATE wp_postmeta SET meta_value = '4 hours' WHERE wp_postmeta.meta_id = 65138;

On Friday at 9am

UPDATE wp_postmeta SET meta_value = '16 hours' WHERE wp_postmeta.meta_id = 65138;

(I followed this answer firstly with regards to $wpdb but am not very comfortable with it to get it right and it’s possibly out of date.)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x