How to Stop WordPress Functions from Running More than Once

I’m going to share what I learned yesterday because it took me about five hours to figure this out and I hope to save other people and myself from having to spend so much time figuring this out in the future. I was working on a plugin for a client that had to fire a function using the init WordPress hook, something done quite often in plugin development. The problem was that this function was running more than one time each time a page loaded. In a perfect world, init should only fire one time per page load, but in real life, it often fires more than once. I’ll get into some reasons for this later, but for now just understand that the problem was related to a PHP function running more than once per page load and I only wanted it to run one time per page load.

The WordPress Init Hook

The WordPress init hook fires after WordPress has finished loading but before any headers are sent. It is very often NOT the best WordPress hook to tie a function too, in fact it should be used quite sparingly! However, should you find a need to use it, this post should help you some I hope. You should only use the init hook if you want something to happen every time any page is loaded. By any page, I mean any admin page or front end page including error pages and everything, so be careful how you use it!

The Main Issue With Init Hook

In my opinion the main issue with using the init hook to call a function in WordPress is that it can be rather unpredictable depending on the state of your WordPress site. For example, the most common issue that can cause the init hook to fire more than once per page load is missing images and missing scripts that are part of the page being loaded but that WordPress can’t find. Every time a page’s image is missing or a script that is linked to the page is missing, a 404 error occurs which in turn fires init yet again. That means if you hook a function into init that opens a pop up window that says “Hello World!”, and the page you open in a browser is missing the header image, then it causes that pop up window to open two times. Now if you happen to be also missing a linked to css file, it could fire even a third time etc…..needless to say, it could be very inconvenient for you as a coder and the end user who has to close all of those nasty pop ups you inadvertently subjected them too…

The Solution

Now, lets say you’ve read to hear and you still want to use the init function or you have no other choice in the matter, then you can do what I did. First I tried several other methods recommended on the internet to stop my function from running more than once. I will list some of those methods here just so you don’t waste your time on them like I did. Please note that some of the methods may work for you if the situation is a little different, but if you are trying to stop a function from running more than once at a time and that function is triggered by the init WordPress hook, then none of the following are likely go work for you:

What Did NOT Work

  1. First I tried simply writing the time to the database ea. time the function ran and also made it so the function read in the time and if it was less than a minute ago, it wouldn’t run the function again in theory. In practice, this doesn’t work! Trust me. Not for this situation at least.
  2. Then I tried using something new to me, semaphore. Semaphores are PHP protected variables used to control access to some resource. They are developed by Dijkstra. I think the reason semaphores didn’t work to stop a function from running more than once was because often times the init hook will fire twice within a hundredth of a second making it almost simultaneious and that doesn’t give the semephore time to work. Don’t expect semaphores to work if you are using the init function and you want to stop a function from firing more than once, but you can learn more about Semaphores here: http://www.re-cycledair.com/php-dark-arts-semaphores. They are interesting, just not for this scenario.
  3. I also tried various methods of saving to the options table using a built-in WP function such as update_option and similar, but everything was too slow to catch the nearly simultaneous firing of the init hook that seem to occur often in WordPress.
  4. The main reason for the init hook firing multiple times per page load to begin with is due to missing images and files as I explained above, so the next thing I tried was to simply clean up the site. If you have a small site, fixing all broken links, images and missing files will probably work for you, but if you have a site like the one I’m working on, forget it! I tried, but quickly found out that it would be a multiple day project to go this route, so I moved on to the next solution. This one however may work for some of you. The way I would go about it is to use Firefox and inspect the page using the web console with the network requests visible. You have to refresh the page after you set them to visible to see all of the network requests. Then simply look for 404 errors and it should tell you all of them for that particular page. You’ll have to do this for every page in the site is why I don’t recommend this solution for larger sites.

What Finally Worked for Me

Now, what worked for me was a combination of things I tried above in a way. I’ll try to keep it short and get to the solution instead of how I came to it because that is a never ending story! Here is some example code that I simplified because this was part of a much more complex and copyright protected solution for a client. This snippet will show you how to stop functions fired by init from running more than one time in the same minute(or whatever interval you set):

<?php
/*
This is example code for how to make a function triggered by the WordPress Init hook only run once per page load and only once per minute or other time interval as set in the code.
*/

//hook a function handler function to init instead of the main function that does the work:
add_action(‘init’, ‘function_handler’, 10, 3);
function function_handler(){
//start out with a random pause from 1 to 5 seconds:
$rn = rand(1000000, 5000000);
log_debug(“Random time was $rn\n”,”a.log”);
usleep($rn);//1000000 is 1sec and 250000 is 1/4 sec etc. 100000 is about 1/10 of a sec.

//get last time the import function was ran from time.txt
$cdir = plugin_dir_path(__FILE__);//get dir of current file with trailing slash
$tFile = $cdir.’time.txt’;
$ftime = “”;//set default value for ftime:
if($file = fopen($tFile, “r”)){
//Output line at a time until end is reached:
while(!feof($file)) {
$ftime = fgets($file);
}
fclose($file);
//log time fetched from time.txt
log_debug(“Time retrieved from time.txt: $ftime\n”,”a.log”);
//log each time this function is called:
}else{
log_debug(“failed to read time.txt time\n”,”a.log”);
}

$lasttime = new DateTime($ftime);//turn time found into a valid DateTime obj.
$dt = new DateTime(“now”);//put the current time into valid DateTime obj.

$dtf = $dt->format(‘Y-m-d H:i:s’);//format $dt or current time to display it
log_debug(“Current time: $dtf\n”,”a.log”);

$lasttimef = $lasttime->format(‘Y-m-d H:i:s’);//format time found to display it
log_debug(“last time ran(according to time.txt): $lasttimef\n”,”a.log”);

//get difference between $dt and lasttime:
$dteDiff = $lasttime->diff($dt);
//format the time difference in a human readable format:
$time_diff = $dteDiff->format(“%H:%I:%S”);
log_debug(“Time since import function last ran: $time_diff\n”,”a.log”);
//see if $time_diff is more than a minute and if not, stop function now!
$comparetime = strtotime(“00:01:00”);//set to max time allowed between function calls!
$timediff = strtotime($time_diff);
if($ftime == ” || $timediff > $comparetime){
//if no time stored yet or time diff is more than a minute, then continue…
log_debug(“ftime was blank or it has been more than a minute since last run so continuing to run import function next!\n”,”a.log”);
}else{//otherwise, kill operation of function because it hasn’t been enough time:
log_debug(“——NOT enough time since last run. import function stopped!\n”,”a.log”);
return;//stops execution of this function here!
}
//code past here only gets executed if it has been more than x minutes since last import
//store time in time.txt:
$fh = fopen($tFile, ‘w’) or die(“can’t open time.txt file to append, Please make sure your follow-hook folder and all files are owned by the www user(user www-data usually). To change ownership you have to access your server command line and issue the command: ‘chown -R www-data:www-data cutivate-crm’ while you are in the wp-content/plugins directory(cd /var/www/yoursite.com/public_html/wp-content/plugins). If problem persists, email developer, Ian L. at linian11@yahoo.com”);
fwrite($fh, $dtf);
fclose($fh);
//go ahead and run your import function now:
import_function();//this is the function that will only get run once!
}//End function_handler PHP function by Ian L. of Jafty.com

function import_function(){
log_debug(“***import_function has been triggered!***\n”,”a.log”);
}//end import_function that can only be ran once a min max.

//Custom function to write data to log file:
function log_debug($log,$filename=’a.log’){
$pdir = plugin_dir_path( __FILE__ );//gets the directory of current file with trailing slash whether inside plugin or not!
$myFile = $pdir.$filename;
$fh2 = fopen($myFile, ‘a’) or die(“Error – can’t open $filename to append…”);
fwrite($fh2, $log);
fclose($fh2);
}//End log_debug PHP function

?>

That’s my solution! Let me explain a little more. The above code is meant to go in a plugin file since this is a technique that should really only be used by plugin developers. It could also go into a theme’s functions.php file, but is less likely to be used there since it depends on other code and isn’t meant to be by itself really. In my case I had a function that imported users into a WordPress site as posts and it had to be done every x minutes, so I had the init hook call the function_handler function. That function_handler function is just to keep the import_function from being called more than one time per minute.

Before I had this set up I had the import_function being called from the WordPress init hook and inside the import_function I logged ea. time it ran to a log file and sometimes when a page was loaded, I would see lines like this in the log file:

Apr,23,2019 07:53:43 PM – check_import_queue function began….

Apr,23,2019 07:53:43 PM – check_import_queue function began….

…and somtimes I might get something like this:

Apr,23,2019 08:03:03 PM – check_import_queue function began….

Apr,23,2019 08:03:04 PM – check_import_queue function began….

…and other times there might be three of these lines or more and sometimes there was only one as it should be, but not often. So, as you can see, some were posting the exact same time and some were only a second apart, so I developed the above code to make them at least be a minute apart to keep my server from getting backed up with import calls. The import function itself was coded to prevent doubles(two of the same person) from being inserted into the post type, but WordPress is not able to catch doubles if the import function was fired within a second or less from the last time it was fired. Therefore without the above code, I would get hundreds of double posts even with code in place to stop it. It simply would not work without the code I wrote above.

The Random Pause

You probably noticed at the start of the code there is a random pause from 1 to 5 seconds. This keeps the function_handler function from writing more than one line to the time.txt file at a time and also will help give WordPress time to do what it has to do in the background as well. I’ve tried it without the pause and it doesn’t work.

Writing to a .txt File

The part of the code that writes the times the import_function was run to a .txt file named time.txt is also part of the trick that makes this work. I could find no other way to store the data fast enough for it to be ready by the next time the init hook fired. I tried storing it in a custom database table and in the WordPress options table, both methods failed. I also tried using a PHP semaphore as I mentioned above and that too failed in my case.

 

Leave a Reply

Your email address will not be published. Required fields are marked *