Our thinking

How to run a one-time WordPress script

15 October 2013

I often find myself writing scripts for WordPress that need to be run one time, and one time only. Usually the scripts are for importing, exporting, migration, or some sort of data manipulation.

After writing several of these types of scripts, I’ve come up with a pretty standard way to do it. Here’s an example:

if ( isset($_GET['run_my_script']) && ! get_option('my_script_complete') ) {
	add_action('init', 'my_script_function', 10);
	add_action('init', 'script_finished', 20);
}

function my_script_function() {
	// this is where your custom code goes
}

function script_finished() {
	add_option('my_script_complete', 1);
	die("Script finished.");
}

Add this code somewhere in your functions.php file. Then, add your custom code in the my_script_function() function. Now go to http://yourdomain.com/?run_my_script to run the script.

After the script gets run, the my_script_complete option is stored in the WordPress database. And the script will not run again after that option is set.