How to Load Content on Demand in WordPress Admin

If you have a WordPress admin page that takes too long to open due to a list of some type or any other content that takes longer to load than you’d like, this solution might be for you.

In my case, I had an admin page for a plugin I’ve been working on a lot lately that has a list of members from another webpage that takes a while to load. What I did was separated that content that fetches the list into another file and placed a link on the page that lets you load the content after the rest of the page has loaded and only if you need to because a lot of the time people aren’t going to need or even want to see that content. Other times they will want to load it and they can now and it won’t take forever to load because the rest of the page already loaded and you only have to wait for that specific content to load, thus making the site much more pleasant to work with… Visit http://chazedward.com/local-seo-coaching/ to have an expert consultation on this issue.

In case anyone is interested that plugin is named Follow Hook, and it adds CRM features to any WordPress site and we just listed it on wordpress.org! Just search for “Follow Hook” and it will come right up.

How To Load Content On-Demand

  1. First, as I mentioned above, you separate the code for just the feature you want to load separately. In my case it was a list of MailChimp subscribers, but it could be any content really. In my case I named my file MC_list_members.php, but you can name yours whatever seems appropriate, just make sure you use the same name below in step 3 where you see the filename in green.
  2. Then you put a link on the admin page you had originally that looks like this: <p><a href=”<?php echo $puri; ?>” target=”hifrm”>View MailChimp Subscribers</a></p>
  3. As you see I have a variable named $puri in the code above and that is going to need to be defined somewhere above where you placed the link. It is the URL of the page that you put your separate code in for the feature you wish to load on demand. In my case I am working on a plugin named Follow Hook so I would use something like this:  <?php $puri = plugins_url(‘MC_list_members.php’, __FILE__); ?>
  4. Then finally, you add your iFrame HTML like this: <iframe id=”hifrm” name=”hifrm” src=”” width=”100%” height=”100%”>Please view this page in a modern browser like Firefox to be able to view this content!</iframe>

Please take note of the name attribute in the iFrame tag because that is what you have to set the target attribute in your link tag too! That is what sends the file with your content in it to the iFrame element on demand and it won’t load until you click the link! Perfect!

JavaScript Auto Complete for Text Field

Yesterday, I had a project that required me to create an auto complete feature for a text field. I searched for an existing solution online and couldn’t find one that fit my exact needs, so I created my own.  I created this particular solution using both PHP and JavaScript, but it could easily be modified to use only JavaScript if you prefer. However, if you have a long list of words or phrases you need to use for the auto complete feature, then you too may want to use PHP to call them into the JavaScript code as I have done.

A Working Example

Let’s start off by showing you a live working example so you can see what we are creating. Here is the link to the example I made as a proof of concept for the project I was working on:

http://jafty.com/test/cities.php

Type of Auto Complete

This particular type of auto complete feature is used on a regular text input field within a form. This auto complete feature is for when you have a list of words and/or phrases that you want to be made available as input into a text field. It is up to you if you want to allow values outside of that list or not. In my case I do not restrict my text field to values from the list, but I did consider it.

Why I Created a New Auto Complete Feature

I made this solution because I was working on a site for the country of Switzerland and had a need to allow Swiss users to enter a Swiss city into a form. I soon discovered that there are well over two thousand villages, towns and cities throughout Switzerland. I found a list that is supposed to contain all of the municipalities in Switzerland online. I wanted to make a script that would use that list for the auto complete feature for the city text field in that form. My solution allows for larger sized word/phrase lists to be employed with the auto complete feature for any text field you assign.

The Solution

Finally, let’s see some code! The code is mostly JavaScript with a bit of PHP. PHP is optional in this case, so if you desire a pure JavaScript solution, simply exclude the PHP file and hard-code the word/phrase list into the JavaScript code.

The Completed Code

Here is all the code from the cities.php file which is a full working example solution when paired with the towns.txt file which has the list of cities in it. Read the instructions provided near the end of this article to learn how to recreate a working example on your own server.

<style>
#town{
border: 1px solid #ccc;
padding-left:20px;
padding-right:15px;
width:165px;
margin-left:100px;
cursor: pointer;
}
</style>
<script>
//isGood JS function checks if char is a valid letter or not:
function isGood(c) {
return c.toLowerCase() != c.toUpperCase();
}

var first = ”;//used in suggest function to hold first letter entered into text field
var second = ”;//used in suggest function to hold 2nd letter entered into text field
var third = ”;//3rd letter…
var fourth = ”;//…
function suggest(c){
//build an array of cities:
var cities = [
<?php
$file = fopen(“towns.txt”, “r”) or exit(“Unable to open towns.txt file!”);
//Output a line of the file until the end is reached:
$line_no=0;
while(!feof($file)) {
$line_no++;
$line = fgets($file);
$curcity = trim($line);
echo “\”$curcity\”,”;
}//end while reading in lines from keywords.txt file
fclose($file);
?>
];
if(isGood(c)){
document.getElementById(‘town’).style.display=”;//shows the suggestions dropdown(town div)
//if only one letter so far:
if(c.length == 1){
//get first letter of c(what was entered into text field) and save it in “first” global variable:
first = c[0].toLowerCase();
}
if(c.length > 1){
second = c[1].toLowerCase();
}else{
second = ”;
}

if(c.length > 2){
third = c[2].toLowerCase();
}else{
third = ”;
}

if(c.length > 3){
fourth = c[3].toLowerCase();
}else{
fourth = ”;
}

con = ”;//empties contents of suggestions saved previously.
cities.forEach(foreachfunction);
document.getElementById(‘town’).innerHTML = ”;//empties the suggested cities first…
document.getElementById(‘town’).innerHTML = con;//fills the town div with suggested cities
}//end if letter is good
}//end suggest JS function by Ian L. of Jafty.com

var con = ”;//init a variable to hold content of the dropdown of suggested cities
//function ran for ea. city in the cities array:
function foreachfunction(city, index){
//get first letter of city:
var f = city[0].toLowerCase();
//see if first matches 1st letter of city(f):
if(f == first){//adds city to suggestions only if first letter is entered in text input:
//if more than one letter has been entered into text field, get 2nd letter of city too:
if(second != ”){//second is blank if only 1 letter, so if it’s not blank get 2nd letter:
if(city.length > 1)var s = city[1].toLowerCase();
if(city.length > 2)var t = city[2].toLowerCase();
if(city.length > 3)var f = city[3].toLowerCase();
if(fourth != ”){//fourth is blank only if 1,2,3 letters, so if it’s not blank, get 4th letter:
if(f == fourth && t == third && s == second){
con += “<div onclick=’addItem(this.innerHTML)’>”+city+”</div>”;
}
}else{
if(third != ”){//third is blank if only 1 or 2 letters, so if it’s not blank get 3rd letter:

if(t == third && s == second){
con += “<div onclick=’addItem(this.innerHTML)’>”+city+”</div>”;
}
}else{

if(s == second){
con += “<div onclick=’addItem(this.innerHTML)’>”+city+”</div>”;
}
}
}

}else{
con += “<div onclick=’addItem(this.innerHTML)’>”+city+”</div>”;
}
}
}//end foreachfunction JS function used within above suggest JS function by Ian L.

//function ran when one of the suggested cities is clicked upon:
function addItem(x){
document.getElementById(‘city’).value=x;
document.getElementById(‘town’).style.display=’none’;
}//end addItem JS function by Ian L. of Jafty.com
</script>
<form>
<table><tr><td>
Village / Town:<input style=”width:200px” type=”text” id=”city” name=”city” onkeyup=”suggest(this.value)” /><br />
<div style=”display:none;” id=”town” name=”town”>
</div>
</td><td>
<input type=”submit” id=”s” name=”s” value=”Suche” />
</td></tr></table>
</form>

The Word and/or Phrase List

In this example we have a long list of Swiss cities as our word list. Your word list can be a list of words and/or phrases which you would like to suggest as values to be entered into the text field for which you are applying the auto complete feature to. Each word or phrase can be as long as you like and should be formatted in a plain .txt file with one word and/or phrase per line. Generally you should probably try to keep your phrases short, but there is no actual limit that I am aware of regarding how long they can be. Just remember this is a “text” input not a “textarea” input, so it is meant for short values typically of one to six words approximately. My list is of city names so they are all relatively short and I’ve formatted the .txt file to list one city per line and saved it as “towns.txt” I have uploaded towns.txt to my personal server, so if you would like to copy it to use for testing your own script, you can do so by going to the following url and simply copying and pasting the word list into your own .txt file and naming it “towns.txt”. Here is the link to towns.txt:

http://jafty.com/test/towns.txt

Instructions to recreate your own auto complete feature

Follow these simple instructions if you want to create the live example on your own server. Then you may modify the code to fit your individual needs.

  1. First, copy the entire code example above in green text and save it to a .php file. I named my file cities.php, you can name yours whatever you like as long as it ends in “.php”.
  2. follow the above link to the towns.txt file and copy and paste it into a new .txt file and name it “towns.txt”. If you choose to name it something else, be sure to also change the name in the code wherever it is used by doing a search and replace for “towns.txt” and replacing it with your new name if you so choose.
  3. Upload both the PHP file and the TXT file to your server inside of the same directory. Then finally, you can visit the cities.php page in your browser and see it work! That’s all there is to it.

Creating a Pure JavaScript Solution Instead

If you prefer to have a pure JavaScript solution and your word list isn’t too large to handle within the JavaScript, follow these simple instructions:

  1. Follow the above instructions, but while doing step no. 1 above, after copying the green text above to a blank file, find the PHP section of code and simply delete it. Delete everything from “<?php” to after the closing PHP tag that looks like this: “?>”.
  2. Then where the php used to be, add the following code but replace the “one, two, three, four” text with your own personal word and/or phrase list.
    “one”,
    “two”,
    “three”,
    “four” , so your cities variable will look like t his now:
    var cities = [
    “one”,
    “two”,
    “three”,
    “four”
    ];
  3. Then you can save your file as an HTML file now since there is no more PHP code in it, so save it as cities.html and open it in your browser and it should work even from your desktop since HTML doesn’t require a server to function like PHP does.

Summary

That’s all there is to it! Feel free to modify this code to fit your needs as you wish. I hope it helps someone else as it did me. I found it very useful myself. I used this on a WordPress site as well, so it is WP friendly FYI.

 

 

 

The Best Way to Learn Mobile App Development

If you start looking into it or have already been researching on ways to learn mobile app development, you come to find out that there is a wide variety of options and decisions you have to make regarding how to learn Mobile App Development. I wrote this guide to help you get started in hopes that it will save you some time and get you coding your own mobile applications faster.

The Many Paths to Learning Mobile App Development

As I mentioned above, there are many different options when it comes to learning mobile app development. Here are just some of the decisions that you will have to make when first getting started with the development of mobile applications:

  • Android, IOS or Cross-Platorm – Do you start out learning to program for Android, IOS or both? What about other Operating Systems? Well the truth is, there really isn’t any other significant Operating Systems, Android and IOS hold about 98% of the market share right now, a mobile development team from UK finds. Worldwide, Android holds 75.22% of the market, while IOS controls 22.76% for a combined market share of 97.98%. So are we worried about the missing 2%? No, not as beginning developers breaking into the market, we’re not. The ratio of Android to IOS users varies significantly from country to country, so if you want to learn more about individual countries, you can go to https://deviceatlas.com/blog/android-v-ios-market-share and read all about it.  U.S. market share is a little bit unclear since I’ve read reports for the end of 2018 that put Android on top and conflicting reports that put IOS on top, so lets just say  it’s roughly 50/50 in the U.S. IOS usage is higher in countries with better economies. As most people know,  iPhones do not come cheap! I just read online that the new iPhone XS is selling for over $1500 dollars! That is much more than I ever care to pay for a phone, but it is impressive with 512gb storage and 4gb of ram. That’s almost as powerful as the laptop I use, amazing! In my opinion, that’s more than most of us need though. There are times when it would be nice, but most of the time I don’t think we need that much power in our cell phones. Surely not the average user at least. So, all arguments aside, Android is the clear winner to me because they have the largest market share world-wide and all of the multi-platform method of mobile app development I’ve seen and tested so far have not been good enough to build commercial applications with yet. So i think you should either pick Android or IOS to start with and eventually learn to develop for both since there is no viable cross-platform option available yet that I’ve seen.
  • What IDE, Framework or coding platform do you use? This question is heavily reliant upon the previous question because it mostly depends on what Operating System you have chosen to develop for. In my case, I’ve chosen to develop for Android first, so after checking out most available options, I’ve decided to go with Android Studio. I selected Android studio because it seems to be the most intuitive and it is very well documented. There’s nothing worse than downloading a new program and finding out that there is hardly any documentation on the web regarding how to operate that program. You won’t have that issue with Android Studio. It came out in May of 2013, so it’s been around for over 6 years now and has built quite the reputation in that short amount of time. I don’t think any of the choices available today are going to have been around for anymore than ten years or so just because the technology is so new. I did try a few other IDEs first and Android Studio was the one that I was able to build a working app the fastest on and it didn’t leave me scratching my head and thinking “Wow, I created an app, but I have no idea how I did it” as some of the other IDE options left me thinking. It’s also important to note here, I feel, that I have no reason to endorse any of the decisions I’ve made in this guide. No one paid me to write this and I do not endorse any products unless I truly think they are the best, but I have not been paid by anyone to endorse anything. So, if I say something is the best, I truly believe it is the best option. It’s as simple as that. That’s hard to believe sometimes in today’s fast paced economy, but it still holds true with me.
  • What coding languages do you learn? Again, this answer is dependent on how you answered both of the questions above, so my choice will only be relevant to your situation if you also choose to develop for Android. The official language for Android development is Java. There is also Kotlin for Android Studio users. Kotlin apps will run on any machine that supports the Java runtime environment and because most machines can, Kotlin is a relatively easy way to create android applications. If you chose to go with IOS on the other hand, Objective-C and Swift are the two most commonly used programming languages for IOS app development. My first choice was Java because it’s been around the longest for use with Android and seems to be the most documented of the two. Kotlin is newer and may have some neat new features, but for now, I’m going with old reliable…

Okay, so that about covers it, the three bullet points above cover the three most important questions you have to ask yourself when you first get into mobile application development. I took my time making the decisions I made to go with Android Studio IDE and the Java programming language to start building mobile apps with, but I can also learn the alternative methods after I perfect these Android application development methods. A true developer is always learning. They say you will need to know about seven different programming languages to be an expert mobile application developer. That sounds about right to me because that’s how many languages I had to learn to be an effective web developer. Speaking of which, I did look into using the languages I already know as a web developer for mobile application development. While there are platforms that make it possible, such as Cordova, in the end they are mostly using techniques to convert the code you write into Java anyway, so I figure it’s faster and more productive in the end to just start learning Java for Android Mobile Application Development. I may look into ways to convert my Java Apps into IOS apps when I am done making some mobile apps with Android Studio, but I suspect I will eventually learn to develop separate apps for IOS in the end.

How to Install NodeJS on Linux Server

In this article, I will cover how to very easily install Node.js on just about any Debian, Ubuntu or other Linux web server. I created this article to fill a great need for accurate information on this subject because I spent the better part of a full day getting Node.JS to work on the first server I had to install it on. Now that I’ve installed it on 3 or 4 different servers, I finally found a quick and easy way to make it work. I also had to make it so node could be called from PHP using the exec command, so it goes one step beyond just installing Node.js.

Here are the Four Quick and Easy Steps for Installing Node.JS on Linux Servers:

(use sudo in front of the command line commands if you are  not root user)

  1. Confirm that Curl is installed using “which curl” from command line and if it doesn’t return the curl location, then install curl before continuing.
  2. Confirm that Node isn’t already installed with the command line command “node –version”. if it doesn’t print a version no. then it needs installed.
  3. Using instructions from https://github.com/nodesource/distributions/blob/master/README.md#debinstall and If on a Debian server, go to command line and run(use sudo if not root user):
    curl -sL https://deb.nodesource.com/setup_8.x | bash –
    …and hit enter….then go to step 4.
    NOTE: if you’re not on a Debian server, follow the relative instructions for your particular server by scrolling to it in the above github URL instead of steps 3 and 4 here.
  4. then run this command from the command prompt(use sudo if not root user):
    apt-get install -y nodejs

Then you can verify that NodeJS works from the command line with:

node –version

and it shold return something like:

8.4.0

 

WordPress Editor is Missing Tabs

I found my site was missing the “Visual” and “Text” tabs along with several other options including the “Kitchen Sink” option that adds the entire second row of menu options to the WYSIWYG editor! So, I was lost without these options and the fix was very difficult to figure out, so I’m going to share it in case someone else has this happen to them.

First off, let me just say that this may not be the solution for you. While searching for the solution, I saw there were several other issues that can cause this, so I’ll go over some of the easy and more common fixes first for you just in case. If the first two solutions don’t work, scroll down to my “The Tricky Fix” section below and give that one a try because that’s the one that got it working for me.

The Easy Fix:

The easy fix is to simply navigate to wp-admin and go to “Users”/”Your Profile” and at the top of your profile admin page you’ll see the “Visual Editor” option with a checkbox that reads: “Disable the visual editor when writing”. All you have to do is make sure this box is NOT CHECKED and then scroll to the bottom of the page and click on the update button to save your settings. Even if it was not checked to begin with, try checking, saving and then uncheck it and save it again and test the post/page editor again and sometimes this alone will make it work, but if it didn’t, keep reading!

The Difficult Fix:

The more difficult but probably second most common fix involves reinstalling or updating WordPress. If that doesn’t work, try disabling plugins one at a time to see which one may be causing the issue. Hopefully one of these first two fixes worked for you because those are the most common ones, however keep reading if you have yet to find a solution that enables your visual editor and missing editor tabs in WordPress. There’s one much trickier solution that is very hard to fine, but rather easy to implement….

The Tricky Fix:

Now for the tricky fix. This fix saved my day! If I hadn’t found it I would have spent all day trying different tricks to fix my Visual Editor and missing buttons issue for my WordPress blog, Jafty.com/blog. It has to do with missing headers and is related to a server issue that I admittedly do not fully understand. All I know is that this fix works if your server has this particular issue as mine did. All you have to do is add a few lines of PHP code to any active plugin or to your theme’s functions.php file. If you are not a plugin developer who happens to be making a plugin at this time, I would add it to my functions.php file. Here is the code:

function richedit_wp_cloudfront () {
add_filter(‘user_can_richedit’,’__return_true’);
}

add_action( ‘init’, ‘richedit_wp_cloudfront’, 9 );

Simply add that to the top of your functions.php file, save it and upload it to your server and refresh the page with the editor on it and it should now work. Mine did. If this doesn’t work, then unfortunately you must have a different sort of issue than I did. I have read online that Amazon servers can have this problem, although it happened to me on a Linode server. Good Luck!

How to get WordPress Version Number

Today I was surprised to find it was a little difficult to find what version of WordPress I was running on my blog. This is mostly due to the fact that WordPress is always changing and evolving, so I decided to share this valuable time saving piece of information with my readers. You can always get the version number from the “At a Glance” dashboard widget in wp-admin.

How to find WordPress Version Number

Simply log in to your wp-admin page and click on “Dashboard” in the left navigation menu. Then look at the resulting page and search for the box with the “At A Glance” heading and click the little arrow to expand it if it’s not already expanded. It will look something like this:

If you don’t see the “At a Glance” box in your dashboard/home admin screen, then it is probably deactivated. I’ll show you how to activate it next.

Activate “At a Glance” Admin Option:

To activate the “At a Glance” box on the home admin dashboard, simply scroll to the top of the page and click on “screen options” and a box with options will slide into view.  In the first “Boxes” section, you will see that “At a Glance” is probably the first option. Make sure the box is checked. Once it is checked the “At a Glance” box should appear on the page. You will find the WordPress version next near the bottom of the “At a Glance” section. Good Luck!

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.

 

WordPress Shortcode Not Showing Up Where It Should?

If you are creating a fantastic plugin or an extraordinary theme or even a lame one of the two, Shortcodes are always fun to work with in WordPress until you run into a situation where the content being generated by the shortcode simply won’t show up where you want it to.

For example after creating a shortcode in a plugin, I tried enter this into a blog post or page today using the WYSIWYG editor :

some content before the shortcode<br />

[my-simple-shortcode]

some content after the shortcode<br />

…and when I saved and viewed the page or post, I got:

my shortcode’s content here…..

some content before the shortcode

some content after the shortcode

….so that is NOT what I wanted clearly and I found a solution!

In simple terms, the solution is not to echo the shortcode content in the shortcode’s function, but to return it instead.

The correct way to create a WordPress Shortcode:

For example, here is how you create a simple shortcode the correct way:

<?php

function create_simple_shortcode(){
    $returnvar = “<p>The content that your shortcode displays…</p>”;
    return $returnvar;
}//end create_simple_shortcode function

//name the shortcode simple_shortcode:
add_shortcode(‘simple_shortcode’,’create_simple_shortcode’);

?>

The wrong way to create a WordPress Shortcode:

In contrast, this is the incorrect way to create a WordPress shortcode using echo instead of return:

<?php

function create_simple_shortcode(){
    $returnvar = “<p>The content that your shortcode displays…</p>”;
    echo $returnvar;
}//end create_simple_shortcode function

//name the shortcode simple_shortcode:
add_shortcode(‘simple_shortcode’,’create_simple_shortcode’);

?>

…this is also NOT correct:

<?php
function create_simple_shortcode(){
    echo “<p>The content that your shortcode displays…</p>”;
}//end create_simple_shortcode function

//name the shortcode simple_shortcode:
add_shortcode(‘simple_shortcode’,’create_simple_shortcode’);
?>

The above could also be done correctly like this however:

<?php
function create_simple_shortcode(){
    return “<p>The content that your shortcode displays…</p>”;
}//end create_simple_shortcode function

//name the shortcode simple_shortcode:
add_shortcode(‘simple_shortcode’,’create_simple_shortcode’);
?>

Get it? return NOT echo! Good luck! hopefully this will save you some time!

What Programming Language is Best for Mobile App Development?


Fatal error: Out of memory (allocated 12582912) (tried to allocate 32768 bytes) in /var/www/html/jafty.com/public_html/blog/wp-content/plugins/php-code-for-posts/PHPPostCode.php(59) : eval()'d code on line 1