I’m developing a WordPress site for a client who is listing celebrities on her site. Each celebrity profile shows a table of social media stats which is grabbed via the relevant API using the respective user handle.
For example the Twitter follower count is retrieved via the Twitter API.
Everything works as it should but the page load times are painful.
I’m now beginning to think it would make much more sense for the server to make the API queries in the background once a week and update the database accordingly, that way we’re not querying the API on every page load.
How would I go about building such a thing?
I’m able to write a function that will loop though all the celebrities grabbing the various data but how do I automate this and ensure the data is entered into the database.
I’m obviously not looking for a complete answer just some guidance on the approach as it’s not something I’ve ever done before and I’m unable to search for something without knowing the relevant terms/names. It’s a bit chicken/egg.
Advertisement
Answer
A sustainable way to do that is to write a plugin that schedules/clear_schedules the cron when activated/deactivated.
Here’s a plugin that you could use.
You will need to either place this in a file (such as custom_cron_event.php) and FTP it to your /plugins folder, or place it in a file and compress (ZIP) the file to upload it to your website through the /wp-admin interface.
You can install a plugin like Cron Manager to verify that the cron event is scheduled. “custom_cron_event” (or whatever name you choose for your function) should be listed as a scheduled cron if you’ve activated the plugin and it is working correctly.
<?php /* Plugin Name: Custom Plugin Plugin URI: Description: Adds function on cron Author: Version: 1.0 */ /* * When this plugin is activated, schedule */ function activate_custom_cron(){ wp_schedule_event( time(), 'daily', 'do_custom_cron_event'); } register_activation_hook(__FILE__, 'activate_custom_cron'); /* * When this plugin is deactivated, clear_schedule cron */ function deactivate_custom_cron(){ wp_clear_scheduled_hook('do_custom_cron_event'); } register_deactivation_hook(__FILE__, 'deactivate_custom_cron'); /* * Function */ function custom_cron_event() { /* * This is where your function goes */ } add_action( 'do_custom_cron_event', 'custom_cron_event' ); ?>