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.

 

Building a Responsive Navigation Menu

In today’s blog post, I’m going to demonstrate how to make a horizontal responsive navigation menu anywhere on your webpage. This tutorial also demonstrates how to make a completely responsive web site if you follow it through. Here is a link to the final product:

http://jafty.com/ResponsiveSite.html

If you want a vertical responsive menu, you can adapt the code accordingly yourself. I am posting this here for reference because it seems like every time I have to do this for a responsive website, I have to relearn it. Now myself and anyone else that needs the technique can find it right here. Another appropriate title for this tutorial could have been how to make a responsive image map since that is what led me to doing this in the first place.

Using Divs Instead of Image Maps

While this tutorial is technically about doing a navigation menu, this exact same method can be used in place of image maps because, if you’ve tried to make a responsive page that has an image map in it, you know it doesn’t work well.

Building a Responsive Nav

First, lets’ build our HTML:

<html>
<head>
<title>test</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<div id="page">
<div id="header-menu-overlay">
<img src="topnav0map.png" style="width:100%;"  border="0" alt="top navigation menu"/>
<div>
    <div>
        <div><a href=""></a></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>
</div>
</div>
</div>
</body>
</html>

To follow along with the tutorial, copy and paste the above code into a new notepad document and save it as test.html. The first div includes an img tag in it as you can see above. Here is the actual image to give you a better idea of what I have done here. So “topnav0map.png” refers to the following image:

topnav0map.png:
topnav0map

Again, if you’re following along, right click on the above image and save it to the same directory as your test.html file. I put the image in a blue background here so you can see it because it is mostly white over a transparent layer done in Photoshop. The reason I use an image here is because it is responsive when you set the width to 100% and height to auto. This is about when I got the idea for an image map to link the items in the nav as you see them in the above image, but quickly found out that image maps do not resize well when changing either the page size or the zoom level when looking at the page live. therefore I used divs as they are more responsive when used properly with percentages as you’ll see below when I get to the CSS part.

Responsive CSS Layout

The most important part is probably the responsive CSS code. Here is what I used:

#page{
position:relative;
width:100%;
max-width:900px;
background-color:#222288;
margin:0 auto;
min-height:1200px;
margin-top:25px;
}

.header_menu_overlay{
position: absolute;
top: 100px;
left:0px;
width: 100%;
min-height: 30px;
text-align: center;
z-index: 99999;
}
.navwrap{
top:-20px;
min-height:27px;
position: relative;
}

.nav_item_wrap{
position:relative;
width:100%;
max-width:1125px;
height:27px;
border: 1px solid brown;
margin:0 auto;
}

.nav_item{
position: relative;
border: 1px solid red;
height: 33px;
display: block;
float: left;
z-index: 999;
}

.nav_item a{
width: 100%;
height: 100%;
position: relative;
display: block;
}

.nav1{
width: 7%;
margin-left: 9%;
}

.nav2{
width: 10%;
margin-left: 1%;
}

.nav3{
width: 10%;
margin-left: 1%;
}

.nav4{
width: 20%;
margin-left: 1%;
}

.nav5{
width: 19%;
margin-left: 1%;
}

.nav6{
width: 10%;
margin-left: 1%;
}

.pg{
position:relative;
width:100%;
max-width:900px;
min-width: 225px;
background-color:#8a1734;
margin:0 auto;
min-height:600px;
margin-top:125px;
}

First, I used the “page” div as a page wrapper by setting a standard 900px width which you may adjust to your needs. I also set width to 100% which is very important for responsive designs, but also notice the max-width is set to 900px this is so your page won’t go crazy-wide when you open a large browser window on a PC. If you want to always cover the width of the screen regardless, then you could remove this, but I recommend using a maximum width myself for most scenarios. Next I’ll include a short description for each CSS declararation after “page” which I just explained:

  • header_menu_overlay – is used to position the overall navigation menu where you want. You’ll see I decided to put it a hundred pixels from the top of the page, but you can put yours wherever you need it even at the bottom of the page for a footer menu if that’s what you need. the header-menu-overlay div is the one that holds the image as well as the rest of navigation divs. Be sure to set the width only of the image in this div and set that width to 100% so it is responsive.
  • navwrap – is the div that wraps the other divs we will use for our links. we set it’s position to relative and top to a negative number to force it on top of the image above it.
  • nav_item_wrap – wraps around the individual menu items and has a margin of “0 auto” so it centers the group of menu items to the rest of the page nicely.
  • nav_item – this class is set to all of the navigation item divs and is used to set their height, display and to float them left which is important for responsiveness.
  • nav_item a – is a style definition for the anchor/link tags inside of the nav_item div. Without this the links will not work. It sets the width and height to 100% of the containing element. You have to set “position: relative”, width and height for this to work.
  • nav1 – nav6 – the next six CSS declarations are used to set each individual menu item’s width and margin-left properties since they can all be different.

Add CSS Classes & Content to HTML:

Okay now we just need to add the classes above in the proper spots in our original HTML code and add some content for each page so that your new HTML page  looks like this:

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel=”stylesheet” type=”text/css” href=”mystyle.css”>
</head>
<body>
<div id=”page”>
<div id=”header_menu_overlay”>
<img src=”topnav0map.png” style=”width:100%;”  border=”0″ alt=”top navigation menu”/>
<div class=”navwrap”>
<div class=”nav_item_wrap”>
<div class=”nav_item nav1″><a href=”#pg1″></a></div>
<div class=”nav_item nav2″><a href=”#pg2″></a></div>
<div class=”nav_item nav3″><a href=”#pg3″></a></div>
<div class=”nav_item nav4″><a href=”#pg4″></a></div>
<div class=”nav_item nav5″><a href=”#pg5″></a></div>
<div class=”nav_item nav6″><a href=”#pg6″></a></div>
</div>
</div>
</div>

<div class=”pg”><a name=”pg1″>page 1</a>
<h1>Place all of your page 1 content here…</h1>
</div>

<div class=”pg”><a name=”pg2″>page 2</a>
<h1>Place all of your page 2 content here…</h1>
</div>

<div class=”pg”><a name=”pg3″>page 3</a>
<h1>Place all of your page 3 content here…</h1>
</div>

<div class=”pg”><a name=”pg4″>page 4</a>
<h1>Place all of your page 4 content here…</h1>
</div>

<div class=”pg”><a name=”pg5″>page 5</a>
<h1>Place all of your page 5 content here…</h1>
</div>

<div class=”pg”><a name=”pg6″>page 6</a>
<h1>Place all of your page 6 content here…</h1>
</div>
</div>
</body>
</html>

Now you should be done and you have a completely responsive website in no time at all! You should go back and remove the borders from the navigation menu’s CSS as those were just for demonstration.

Summary

So if you followed this tutorial, you should have learned quite a bit about responsive design. Not only should you be able to grasp how to develop a navigation menu from this article, but you should now be able to understand how to replace an inline image map with responsive divs and even how to make an entire responsive website using the techniques demonstrated here. Remember to use percentages instead of pixels for widths and even heights wherever you can and your design will be responsive and evenly laid out for all devices. Congratulations, you are now a responsive developer if you understood all of this. Good Luck!

View outcome of tutorial here:

http://jafty.com/ResponsiveSite.html

 

 

How to Identify a Font

Today I was challenged with figuring out what a font was that a client wanted. He had sent me an image of some text with the font he wanted, but no name and no example HTML code to look at. So what did I do? It wasn’t easy at first until I found some helpful sites on the internet.

Identify Font From Image

A site to help you discover what a font is from an image:

http://www.myfonts.com/WhatTheFont/

The above website allows you to idenfy a font by uploading an image of the font then asking a series of questions about what letter is what. A tip is to take an image of the font that is about 14 characters long and save it as a .jpg before uploading to that site.

Identify Font by Answering Questions

Here is another site that will help you figure out what a font is just by answering a series of multiple choice questions about the font in question:

http://www.identifont.com/

Just answer the first question on that page on the left site and keep on going until it gives you the answer you were seeking with several alternative fonts from which your font will most likely be one of.

Summary

I used both above methods successfully after years of having issues identifying fonts, so I thought I should share them.

How to Add Custom Fonts to Windows

Here we discuss how to add fonts to your Windows OS. You may find this necessary to use new fonts in Photoshop or any other program running under the Windows OS.

Here are the simple steps:

  1. download the .ttf file from any free fonts website such as one I found here: http://www.dafont.com/
  2. unzip the file you download from dafont.com and from your Windows desktop, simply double click on the .ttf file(s) one at a time and Windows will know what to do with them. You’ll only have to click the “Install” option in the pop up window that opens when you double click on the .ttf file.

Summary

Yes, that’s really all there is to do! Now open your Photoshop or other program you wanted to use a custom font in and it will be there now! Just like magic!

How to Add Custom Fonts to Any Website

Today we are exploring how to add custom fonts to any website including WordPress. First let’s take a quick look at the basic available font formats:

Font Formats:

TTF – Works in Firefox and most decent browsers but does NOT work IE and iPhone.
EOT – IE only because they have to be difficult.  EOT is an acronym for Embedded Open Type. The format was created by Microsoft (the creator of @font-face) over 15 years ago. It’s the only format that IE8 and below will recognize when using @font-face.
WOFF – Web Open Font Format. Created for use on the web, and developed by Mozilla, it is the compressed, emerging standard. Should soon work with ALL modern browsers!
SVG – SVG or Scalable Vector Graphics fonts are For iPhone/iPad. Its the only format allowed by Safari version 4.1 and below. iPhoneSVG fonts are basically for older versions of iOS Safari (3.2-4.1).

Here is how to embed custom fonts on your website using the @font-face property of CSS:

  1. First be sure to have at least a true type font file and a .woff file because .woff is for modern browsers including Firefox while true type fonts are for some versions of Firefox, safari, android, etc. browsers. so if you only have a .ttf file for your new font, use an online file converter to convert the .ttf file to a .woff file like the one found HERE: http://everythingfonts.com/ttf-to-woff
  2. find your site’s main CSS style sheet and add the following code to the start of the file:
      @font-face{
    font-family: ‘shapefont’;
    src:  url(‘fonts/OptimusPrinceps.woff’) format(‘woff’), /* Modern Browsers */
    url(‘fonts/OptimusPrinceps.ttf’)  format(‘truetype’);/* Safari, Android, iOS */
    }
  3. Then simply declare your font wherever needed in the site’s css sytles using the new font-family you created so an example CSS delaration for the above font which I named “shapefont” would be:
    font-family: shapefont;

NOTE: if you copy and paste, you’ll need to replace all quotes, single and double because this site uses fancy ones that don’t work with CSS code.

Using Free Web Font Kits from FontSquirrel.com

A quick and easy way to make sure that you have fonts that will work in all browsers and devices is to include all four basic font types, tff, wof, eot and svg. An easy way to assure that you can get all four in a nicely wrapped font kit is to use Font Squirrel. Here are the simple instructions for geting a complete free font kit from Font Squirrel:

  1. Go to http://www.fontsquirrel.com/fonts/list/find_fonts and you’ll see a list of the fonts available through Font Squirrel.
  2. Click on one of the fonts(not on the download button because that is for one font type only).
  3. Then select the “webfont kit” tab on that font’s page.
  4. Make sure that all 4 file types are checked then click on the button that reads “DOWNLAD @FONTFACE KIT” and click “ok” to download to your computer.
  5. Unzip the zip file on your desktop and open it. You’ll see a file named “How_to_use_webfonts.html” which will have step by step instructions on how to install the fonts from here.

A Sure-Fire Method to Make your Font Work

I understand that the instructions from Font Squirell can be a little vague, so here is my sure-fire method for installing a web font kit and this method will work with fonts from anywhere by the way.

  1. After you have your font files(steps 1-5 above). Make a new folder on your desktop named “mysite”.
  2. put your HTML page or a test HTML page into your “mysite” folder.
  3. Inside of the head tags in your HTML page, add:      <!–Custom fonts:–>
        <link rel=”stylesheet” href=”font.css” type=”text/css” charset=”utf-8″ />
  4. Create a new CSS file called font.css and paste the following code into it: @font-face{
    font-family: ‘MyFont’;
    src: url(‘WebFont.eot’);
    src: url(‘WebFont.eot?iefix’) format(‘eot’), url(‘WebFont.woff’) format(‘woff’), url(‘WebFont.ttf’) format(‘truetype’), url(‘WebFont.svg#webfont’) format(‘svg’);
    }
  5. In line two of the above code, where font-family is declared, change “MyFont” to whatever you want to call your new font. This is the name you will use to call your font by in your regular style sheet.
  6. Save the font.css file and put it inside your “mysite” folder with your HTML page.
  7. Move your .wott, .eot, .ttf and .svg font files into the same “mysite” folder as the HTML and CSS files. If you are using a Font Squirrel kit, open the folder you unzipped earlier, find the “web fonts” folder inside and select the one you want. There are different types such as light, medium, bold etc. for most fonts. You may choose to install more than one type. If so, simply repeat the process for each type and give it a unique font-family name. If you’re not sure which folder has your font files, use the one that ends with “regular_macroman” and open it. copy the .svg, .eot, .wott and .ttf files into your “mysite directory.”
  8. Take the name you named your custom font(originally MyFont”) in steps 4 & 5 above and use it in your web page’s CSS style sheet. If you don’t have one yet, create a new file called style.css and add the following code to it:

    body{
    font-family: “MyFont”;
    }

  9. Save your style sheet as style.css if you made a new one. If you had an existing CSS file already, modify the font-family declarations you want to include the custom font name you created for “MyFont”. Simply replace whatever comes after “font-family:” with the name of your new font wherever you want to use it and you are done!

 Summary

That’s really all there is to it. The Font Squirrel method just described was made simple by putting everything in the same folder. You’ll probably desire a different structure, so be sure to change any file paths accordingly if you do so. If you’re doing this to a WordPress website, just locate your current theme’s style.css file and add the @font-type declaration shown above to the top of the file then add the font you named wherever you like in the site using the font-family declaration. It’s easy as pie! Good Luck!