WordPress consultant

WordPress run once only

Background:

Say i have a function i need to run only once, Well WordPress will let you do that if you call that function inside a plugin using register_activation_hook but every time the plugin is activated.

Problem:

I have a function i need to run once only at the activation of my theme, or simply using the some code in my functions.php file.

Solution:

I wrote this handy little class that i based on WordPress conditional tags.

/* 
* run Once class
* 
*/
if (!class_exists('run_once')){
	class run_once{
		function run($key){
			$test_case = get_option('run_once');
			if (isset($test_case[$key]) && $test_case[$key]){
				return false;
			}else{
				$test_case[$key] = true;
				update_option('run_once',$test_case);
				return true;
			}
		}
		
		function clear($key){
			$test_case = get_option('run_once');
			if (isset($test_case[$key])){
				unset($test_case[$key]);
			}
			update_option('run_once',$test_case);
		}
	}
}

Usage:

Let say that my function is called do_something and i want i only need to run it once Ever

// create a new instance of the class
$run_once = new run_once;
if ($run_once->run('do_stuff')){
	do_stuff();	
}

But but what if i want to reset the conditional check for a specific key so it will run once more? Still very simple:

// create a new instance of the class
$run_once = new run_once;
$run_once->clear('do_stuff);

Install:

Copy this code in to your theme's functions.php or include it in your plugin file.

Parameters:

Both function of the class take only one parameter:

$key - (string) the name of your conditional run once check.

As always feedback is more the welcome.

Ohad Raz

WordPress Consultant, a WordPress Developer and a WordPress Freelancer With over 10 years experience in architecting web sites and applications. WordPress Development moderator and somethimes Plugin Developer.