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?

If you’re a web developer and are considering getting more into mobile application development for IOS and/or Android operating systems for mobile phones, then you are likely go ask the question, “What Programming Language is Best for Mobile App Development?”.

The answer is somewhat complicated because there are many answers. To narrow down the possible options, I am going to make a couple assumptions. I will assume that you, like myself, like to stay away from platforms and drag and drop type UI tools to program with. I will also assume that you want to develop something for both Android and iPhone, not just one or the other.

Considering the above assumptions, there are still many options, so what makes it such a complicated choice? In my opinion the main factor that makes it so difficult to pick a coding language to specialize in for mobile app development is the fact that there are two main and competing mobile platforms that have chosen to use different languages with their operating systems. Of course I am speaking about Android Vs. iOS.

Android Vs. iOS, Which is More Popular?

A quick Google search shows me that just over 85% of smartphones are Android, while most of the remaining 15% are Apple iOS phones. According to an article I read on 9to5mac.com, Android and iOS together account for 99.1% of all smartphones in use today, which makes any other devices almost pointless to develop for. It is worth mentioning that of the 0.9% of devices that are not running Android or iOS operating systems, are mostly running Windows operating systems. Windows OS accounts for  0.6%, while 0.1% are Blackberry and the remaining 0.2% are various other operating systems that are not popular enough to be worth even mentioning here.

Best Languages for Android OS

JAVA

Since Android controls the majority of the market for smartphones today, let’s look at them first. If you are going with the most popular answer, than Android wins by far! Android operating systems use Java. If you are coding an app for Android phones, Java is most likely going to be your best programming language to choose as the base language for your app. In reality, many apps use a combination of several different languages. However, in my experience your language of choice will make up the majority of the app’s code.

Kotlin

Kotlin, a second app development language option, was designed and developed by JetBrains. They are a Czech company known for the popular IDE, IntelliJ IDEA. Google’s Android team recently announced that they are officially adding support for the Kotlin programming language. Kotlin was created to address some of the Java issues. Some say the Kotlin syntax is clean, simple, and leads to less code bloat.

Best Languages for iOS

While Apple’s iOS operating system only accounts for roughly 15% of the smartphone market, that is still a significant number of devices out there. Smart developers create apps for both Android and iOS, whether it be with separate apps for each or some sort of platform used to create a mashup that will allow a single app to function on both operating systems.

Apple iOS apps primarily use SWIFT or Objective-C

SWIFT

SWIFT is a quickly growing open source language popular with many starting out with app development today. Apple has heavily promoted the use of SWIFT making it clear that they intend for SWIFT to be the leading language choice for iOS application developers.

Objective-C

Objective-C was the original language of the iOS operating system, but is being phased out apparently since Apple is making it clear that SWIFT is the future, then that leaves Objective-C stuck in the past. While it is still a viable option, I would suggest using it only on an as-needed basis for iOS application development purposes.

Cross -Platform Mobile App Language Options

For some of you, particularly those of you who don’t want to make two separate apps, a cross-platform language option might seem more attractive. A cross-platform language in this context, is one that will allow a mobile application to function on both Android and iOS without the need to make two applications, one for each OS.

JavaScript

If you started out as a web developer as I did, then you are surely familiar with JavaScript. Not to be confused or associated with Java, JavaScript is it’s own language despite the similar name. JavaScript is very versatile in that you can complete many different types of tasks using the language. It is probably one of the most popular cross-platform options because it is effective and rather light-weight.

Several JavaScript frameworks exist today that target the mobile application development market. While I am not a huge fan of most frameworks in general, some of these deserve some serious consideration none-the-less. Some of the well known JavaScript frameworks popular today include PhoneGap by Cordova, Angular.js, jQuery Mobile and React. There are many more that are worth researching if you are looking for a cross-platform JavaScript framework or library to help build your next mobile application for Android and iOS. Actually, JavaScript apps will also work on the other less used Operating Systems as well such as Windows OS and Blackberry.

Using Ajax on Admin Page in WordPress Plugins

Today, I’m writing a rather simple WordPress Ajax example that demonstrates how to user Ajax in a wp-admin page from a WordPress Plugin.

Using Ajax in wp-admin is a little easier than using it on the front-end of a WordPress site because of the ajaxurl JavaScript global variable which refers to the admin-ajax.php url.

In the following code example the goal is to provide an admin page with a delete post link that is powered by Ajax. Therefore the code enables the deletion of a WordPress post without the obtrusive page refresh!

This is a pretty bare-bones example meant as a learning tool. It could be fleshed out much more to be more practical, but I wanted to keep it simple to get the main point across, which is how to do a simple Ajax request from wp-admin.

The Essential Code

First, for those of you that only need to see the basics, I’ll demonstrate the essential code for the Ajax to work. Further down this page, I’ll put it all together in a simple plugin for those of you that may need to see a working example to grasp the concept better. Here is the essential code to enable an Ajax delete post button:

First, a simple HTML line to call our JavaScript function onclick:

<span onclick=’ajax_delete_posts(<?php echo $ID; ?>)’ style=’color:red;cursor:pointer’ title=’Delete Person!’>X</span> <?php echo $title; ?><br />

In the above, you’ll notice the ajax_delete_posts JavaScript function is called. ajax_delete_posts is the function we must create! Of course you’ll need to define the post id in $ID and the post tile in $title using PHP, but this is just to show you how I intend to call the Ajax/JavaScript function

Second, we use PHP to generate our ajax_delete_posts function in JavaScript code:

You can rename the ajax_delete_posts as you wish, just make sure to rename it in your HTML above too if you do. Here’s the code to generate the JavaScript from within your PHP file, the plugin’s main file normally:

<?php

//add Ajax for deleting posts or custom post type(replace ‘post’ with cpt name):
add_action(‘admin_footer’, ‘del_posts_js’);
function del_posts_js() {
?>
    <script type=”text/javascript” >
    function ajax_delete_posts(t) {

        var data = {
            ‘action’: ‘del_posts_with_ajax’,
            ‘t’: t
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(ajaxurl, data, function(response) {
            alert(‘Ajax server response: ‘ + response);
        });
    }//end Ian’s JS AJAX function
    </script>
<?php
}

?>

Notice in the above code how we pass the post id to the JavaScript function using the “t” variable. Also it’s important to note your data variable’s action value as you will need to use the same value for the function name in the below code. Feel free to use whatever text you want for the action as long as it can be an appropriate PHP function name in the code below as well.

Finally, the third step is to add your PHP function named after the action named above and also hook into it with “wp_ajax_” followed by the action named above as well, so in our case the hook we use would be “wp_ajax_del_posts_with_ajax”. However, if you use a different action, such as “do_aj” for example, then your action hook would read “wp_ajax_do_aj”. Got it? I hope so, but the code example should help too, so here it is:

<?php
add_action( ‘wp_ajax_del_posts_with_ajax’, ‘del_posts_with_ajax’ );

function del_posts_with_ajax() {

    $tpidof = $_POST[‘t’];
    
    if(wp_trash_post($tpidof)){
        echo $tpidof.” Deleted!”;
    }else{
        echo “$tpidof Failed to delete!”;
    }

    wp_die(); //required to terminate immediately and return response!
}
?>

In the above code example, we first set up our action hook by using the hook “wp_ajax_” followed by the action we used in the “var data” line further above.  Then we write a PHP function named exactly like the action we used above and be sure to also name the function as the parameter in the action hook as well and you will be good to go!

Putting it all together in a simple Ajax WordPress Plugin

Next I’ll show you the example plugin I created to demonstrate exactly how this all works together in case some of you failed to grasp it from my previous explanations. You can cut and paste the following PHP code into a file named “ajax_post_delete.php” and place it on your desktop in a folder named “ajax_post_delete” and I promise you the code will function on any standard WordPress installation as of the day I wrote this. Here is the complete “Ajax Post Delete” WordPress plugin code in a single file example plugin:

<?php
/*
Plugin Name: Ajax Post Delete
Plugin URI: http://jafty.com/ajax_post_delete

Description: A plugin used in the article at http://jafty.com/blog/?p=10739 in order to demo an admin ajax example

Author: Ian L. of Jafty.com
Author URI: http://jafty.com

Version: 1.0.0

License: GNU General Public License v2.0
License URI: http://www.opensource.org/licenses/gpl-license.php
*/

//function to add wp-admin menu:
add_action(‘admin_menu’, ‘add_ajax_post_delte_admin_menu’);
function add_ajax_post_delte_admin_menu() {

    $page_title=’Delete posts’;
    $menu_title=’Delete posts’;
    $capability=’manage_options’;
    $menu_slug=’del_posts_pg’;
    $function=’mk_dele_pg’;
    $icon_url = ”;
    $position=’4′;
    
    add_menu_page($page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position);
    

}//————end add_ajax_post_delte_admin_menu function——————

function mk_dele_pg(){
?>
<h1>Delete posts</h1>
<?php
//get all posts:
$args = array(
‘post_type’ => ‘post’,
‘posts_per_page’=>-1
);
global $wp_query;
$wp_query = new WP_Query($args);
//start looping posts
while($wp_query->have_posts()) : $wp_query->the_post();
$person = get_the_title();
$personID = get_the_ID();
//echo $person.”<br />”;
echo “<span onclick=’ajax_delete_posts($personID)’ style=’color:red;cursor:pointer’ title=’Delete Person!’>X</span> $person<br />”;
endwhile;

}//end mk_dele_pg function

//add ajax for deleting touchpoint history for posts CPT:
add_action(‘admin_footer’, ‘del_posts_js’); // Write our JS below here

function del_posts_js() {
?>
    <script type=”text/javascript” >
    function ajax_delete_posts(t) {

        var data = {
            ‘action’: ‘del_posts_with_ajax’,
            ‘t’: t
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(ajaxurl, data, function(response) {
            alert(‘Ajax server response: ‘ + response);
        });
    }//end Ian’s JS AJAX function
    </script>
<?php
}

add_action( ‘wp_ajax_del_posts_with_ajax’, ‘del_posts_with_ajax’ );

function del_posts_with_ajax() {

    $tpidof = $_POST[‘t’];
    
    if(wp_trash_post($tpidof)){
        echo $tpidof.” Deleted!”;
    }else{
        echo “$tpidof Failed to delete!”;
    }

    wp_die(); //required to terminate immediately and return response!
}

?>

That’s it! copy and paste the above code into your .php file and you’ve got a simple WordPress plugin that will demonstrate the use of Ajax effectively in a custom admin page of your WordPress website. Feel free to modify the code as needed, but please change the plugin name if you intend to distribute it. Thank you and Good Luck!

Adding Custom Field to WordPress Quick Edit UI for Custom Post Type

Adding a custom field to the WordPress Quick Edit screen for a custom post type was a rather tricky task, so I wanted to be sure to share my solution with my readers in case any of you have a difficult time with it as well.

Let’s get our hands dirty shall we?

There are six basic high level steps to adding a field to quick edit which are:

  1. Add a new column to the posts screen for the post type – I thought this was not necessary at first, but I assure you that it is 100% required for the new field to work within the quick edit UI. Therefore if this turns you off, you can surely find a way to hide the field from view if you don’t want it to show up on the posts admin screen.
  2. Fill the column you added in the previous item with data – While this step isn’t actually required for the field to work in the quick edit screen, it is needed if you wish for the column to have relevant data in it. However, if you wish to hide the column as I suggested could be done, then you may surely skip this step. I don’t recommend skipping it however.
  3. Add HTML code to the Quick Edit User Interface – this will be accomplished, as you’ll soon see below, with WordPress’s quick_edit_custom_box action hook and your custom HTML for your custom field.
  4. Save the new custom field’s value that you’ve added to the Quick Edit UI – This can be easily achieved by making use of the WordPress save_post action hook as you will discover below.
  5. Add some JavaScript code in the admin page’s footer to update your custom fields value within Quick Edit UI – this is where it gets a little tricky for some. I’ll explain as best I can below, but suffice it to say for now that you have to update the input field you created in the quick edit menu with JavaScript that’s generated with PHP code using WordPress’s admin_footer hook. I have seen some alterations of this in other posts online where people use JQuery, but I tend to find that using JQuery is often more likely to lead to plugin conflicts if you are not very careful, so I prefer to use plain JavaScript whenever possible.
  6. Finally you’ll need to link your JavaScript function from the previous step to the Quick Edit link for each post using a JavaScript OnClick event – this is done with the elusive WordPress filter named post_row_actions that allows you to change the context of the Quick Edit link itself with some PHP magic.

Now that the high level steps have been explained in very little detail to give you an idea of what we’ll be doing in this tutorial, I will demonstrate each step with a working code example that you can use to paste into your own Plugin or Theme files as needed. If you don’t know where to paste the code, then frankly, this tutorial may not be for you, so I won’t go into that part in detail since this tutorial is really meant for plugin developers and all of them surely know where to place the code I’ll be showing below.

Step 1 – Add a new column to the posts screen for the post type

Step 1 is by far the easiest step with very little code. All we need to accomplish here is to add a column to the Custom Post Type admin screen. Here is the simple PHP code:

<?php

//Add groomer Column to dogs CPT:
add_filter(‘manage_dogs_posts_columns’, ‘dogs_groomer_post_column’);
 
function dogs_groomer_post_column($columns) {
    $columns[‘groomer’] = ‘groomer’;
    return $columns;
}//end dogs_groomer_post_column PHP function

?>

Not a lot you need to do to the above code but change the custom post type name and the field name to your own CPT and Custom Field Name, so search and replace “dogs” with the name of your Custom Post Type. Then search and replace “groomer” with your custom field name. Your now done with step 1! Don’t worry, they will get harder!

Step 2 – Fill the column you added in the previous item with data

Now all we have to do in step 2 is fill our column from step 1 with relevant data. In our case, the name of the groomer for each dog in the dogs custom post type. Here’s the PHP code:

<?php

//Add content to new groomer Column in wp-admin for dogs cpt:
add_action(‘manage_posts_custom_column’, ‘render_groomer_column_for_dogs’, 10, 2);
 
function render_groomer_column_for_dogs($column_name, $id) {
    switch($column_name) {
    case ‘groomer’:
        // show groomer
        $groomer_val = get_post_meta( $id, ‘_groomer’, TRUE);
        if($groomer_val == ”)$groomer_val = ‘None’;
        echo $groomer_val;              
        break;
    }
}//end render_groomer_column_for_dogs PHP Function

?>

Again, all you have to do to make this code your own is replace “dogs” with the name of your custom post type and replace “groomer” with the name of your custom field and be sure to get the ones with the underscore in front of them too! I like to put underscores in front of field names when saving them to the database. That’s all for step 2! Another easy one! Okay on to step 3.

Step 3 – Add HTML code to the Quick Edit User Interface

In step 3 we have to add a PHP function using the quick_edit_custom_box WordPress hook that adds HTML content to the Quick Edit User Interface. Here’s the PHP code:

<?php

//add groomer to quick edit screen:
add_action(‘quick_edit_custom_box’,  ‘CCRM_add_groomer_to_quick_edit’, 10, 2);
 
function CCRM_add_groomer_to_quick_edit($column_name, $post_type) {
    if($column_name != ‘groomer’) return;
    ?>
    <fieldset class=”inline-edit-col-left”>
    <div class=”inline-edit-col”>
        <input type=”hidden” name=”groomer_noncename” id=”groomer_noncename” value=”” />
<label for=”groomer_status”><?php _e(‘groomer: ‘, ‘dogs’); ?><select name=”groomer_status” id=”groomer_status”>
    <option>-Pick one-</option>
    <option>Ted Dogly</option>
    <option>Teresa Lassie</option>
    <option>Megan Dame</option>
    <option>Star Wolfe</option>
    <option>Joan Smith</option>
    <option>Dober Mann</option>
    </select></label>
    </div>
    </fieldset>
    <?php
}//end CCRM_add_groomer_to_quick_edit PHP function

?>

Again to make the above code your own, you’ll want to replace all occurrences of dogs and groomer with your own names as in the previous two steps. Another option you may wish to change in the above code will be the input type. Here we have decided to use a select input to create a drop-down of possible groomer names to assign to each dog. You may prefer to use a text field, checkbox or even a textarea here, you can use any form element you want to collect your custom field’s data. Simply change the above code to fit your individual needs and your done with step 3!

Step 4 – Save the new custom field’s value that you’ve added to the Quick Edit UI

In step 4, we save the new custom field value to the WordPress database when it is edited from the Quick Edit dialog. As with all the previous steps, change the names of dog and groomer according to your own post type and field name respectively. In the below code we use the common “save_post” WordPress hook to detect when a new field value is submitted and save it with the following PHP code:

<?php

//save groomer for quick edit screen:
add_action(‘save_post’, ‘save_groomer_quick_edit_data’);
 
function save_groomer_quick_edit_data($post_id) {
    $post = get_post($post_id);
    //verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything:
    if(defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE)
        return $post_id;    
    //Check permissions
    if(‘dogs’ == $post->post_type){
        if(!current_user_can(‘edit_page’, $post_id ))
            return $post_id;
    }   
    //OK, we’re authenticated: we need to find and save the data
    
    if(isset($_POST[‘groomer_status’]) && ($post->post_type != ‘revision’)) {
        $groomer = esc_attr($_POST[‘groomer_status’]);
        if ($groomer)
            update_post_meta($post_id, ‘_groomer’, $groomer);     
        else
            delete_post_meta($post_id, ‘_groomer’);     
    }       
    if(!isset($groomer))$groomer=”;
    return $groomer;  
}//End save_groomer_quick_edit_data PHP function

?>

The above code is fairly straight forward, so simply change dogs and groomer text as with previous steps and move on to step 5 below.

step 5 – Add some JavaScript code in the admin page’s footer to update your custom fields value within Quick Edit UI

Here is where it gets a little tricky! There’s no simple PHP code to update the Quick Edit UI with the latest updated field value, so we have to generate some JavaScript with the following PHP code. We’ll use the admin_footer WordPress hook to inject JS code into the footer of the admin page like so:

<?php

//add JS to footer that updates quick edit dropdown:
add_action(‘admin_footer’, ‘groomer_quick_edit_JS’);
 
function groomer_quick_edit_JS() {
    global $current_screen;
    if(($current_screen->id != ‘edit-dogs’) || ($current_screen->post_type != ‘dogs’)) return;
     
    ?>
    <script type=”text/javascript”>
    <!–
    function replace_quick_edit_link(widgetSet, nonce) {
        //alert(‘set_inline….’);
        //revert Quick Edit menu so that it refreshes properly
        inlineEditPost.revert();
        var widgetInput = document.getElementById(‘groomer_status’);
        var nonceInput = document.getElementById(‘groomer_noncename’);
        nonceInput.value = nonce;
        //check option selected
        for(i = 0; i < widgetInput.options.length; i++) {
            if(widgetInput.options[i].value == widgetSet) {
                widgetInput.options[i].setAttribute(“selected”, “selected”);
            }else{widgetInput.options[i].removeAttribute(“selected”);}
        }
    }//End replace_quick_edit_link JavaScript Function
    //–>
    </script>
    <?php
}//End groomer_quick_edit_JS PHP function

?>

Now the above code maybe a little complicated for some, especially those of you who want to use a different type of form field rather than use the drop-down select like in our code. Where you see the section of code that has the comment “//check option selected” before it is where you’ll need to make significant code changes if you use anything other than a select field in your own code. Also be sure to also change all occurrences of dog and groomer as in each of the previous steps.

Step 6 – Link your JavaScript function from step 5 to the Quick Edit link for each post using a JavaScript OnClick event

Next due to the fact that it’s impossible to update the option updated in the quick edit UI, we use the following PHP and JS magic to make it happen with the help of the WordPress post_row_actions filter hook:

<?php

//code to modify quick edit link with on-click event:
add_filter(‘post_row_actions’, ‘groomer_expand_quick_edit_link’, 10, 2);
 
function groomer_expand_quick_edit_link($actions, $post) {
    global $current_screen;
    if (($current_screen->id != ‘edit-dogs’) || ($current_screen->post_type != ‘dogs’)) return $actions;
 
    $nonce = wp_create_nonce(‘groomer’.$post->ID);
    $groomer_val = get_post_meta($post->ID, ‘_groomer’, TRUE);
    $actions[‘inline hide-if-no-js’] = ‘<a href=”#” class=”editinline” title=”‘;
    $actions[‘inline hide-if-no-js’] .= esc_attr(__( ‘Edit this item inline’ ) ) . ‘” ‘;
    $actions[‘inline hide-if-no-js’] .= ” onclick=\”replace_quick_edit_link(‘{$groomer_val}’, ‘{$nonce}’)\”>”;
    $actions[‘inline hide-if-no-js’] .= __( ‘Quick&nbsp;Edit’ );
    $actions[‘inline hide-if-no-js’] .= ‘</a>’;
    return $actions;    
}//end groomer_expand_quick_edit_link PHP function

?>

Changing each occurrence of dogs and groomer in the above code should be sufficient in most cases to make it your own. Good luck!

Going a Step Further with Bulk Edit Ability Too!

Okay, this technically makes it seven steps instead of six, but I added this as an afterthought because it is so easy to add the bulk edit feature to the above code. All you have to do in order to make the same custom field from the above code show up in the bulk edit screen or UI, is add one line of code! Therefore I thought it wise to add it here.  Here is how:

If you look above at step 3, the first line of PHP code is the quick edit hook which looks like this:

add_action(‘quick_edit_custom_box’,  ‘CCRM_add_groomer_to_quick_edit’, 10, 2);

All you have to do to also make the same field show up in the bulk edit screen too is add the following code that contains the bulk_edit_custom_box hook in place of the quick_edit_custom_box hook in the above line of code like this:

add_action(‘bulk_edit_custom_box’,  ‘CCRM_add_groomer_to_quick_edit’, 10, 2);

That’s it! you can add the above l line directly before or after the quick_edit_custom_box hook as in step 3 above. Now if you select all posts from the custom post type screen and then in the “bulk actions” dropdown, select “edit” and you can edit the new custom field value for all of your posts at one time! Yes, we saved the simple step for last! Enjoy your new bulk and quick editor plugin!

Summary

In conclusion, you’ll want to incorporate the above code examples into your own plugin for best results. I have created such a plugin for anyone who needs it. Please feel free to contact me by email at linnian11@yahoo.com if you would like the plugin.

WordPress Post Link Not Working

If you’ve been using WordPress for a good length of time now, you have likely come across a time when you published a post and tried to visit the page and it gave you a 404 not found error, right? Of course I’m right or you probably wouldn’t be here reading this, so here are a couple common fixes you should try first when this happens.

Re-Save Permalinks

The first thing I always try is to simply go to wp-admin/settings/Permalinks and make sure the settings are correct and even if they are, save them again just by clicking the button at the bottom of the page even if you do not change a thing! This will often fix your problem, but not always.

Re-Name Your Post and Permalink

Sometimes simply giving your post a new name and changing the Permalink at the top of the page will resolve the problem as well. To do this, simply change the title by adding a word or two and then change the permalink right under the title by changing it to match the new title but make it all small letters and replace spaces with hyphens. One reason this might work is if you had accidentally used a reserved word for your title  or a title that exists for some other purpose in WordPress. When that happens it will simply ignore it and show you a 404 link instead usually. If you do not want to change your posts title, then you can probably get away with just changing the permalink right under the title, but you always have to change the permalink at least to be sure you’re not using a reserved word or link that is already in use somewhere else within WordPress.

 

 

Basic WP Cron Jobs

This is going to be a simple WP Cron tutorial that explains the basic use of WordPress cron, the wp_schedule_event function and it’s 3 built in intervals. I’ll write a more complex one soon that explains how to add your own intervals, but this is a good starting point:

Practical Code Example

<?php
//Add function to register daily function on WordPress init
add_action( ‘init’, ‘register_daily_cron’);

// Function which will register the daily event:
function register_daily_cron() {
    // Make sure event hasn’t been scheduled already:
    if(!wp_next_scheduled(‘daily_cron’)) {
        // Schedule the event
        wp_schedule_event(time(), ‘daily’, ‘daily_cron’);
    }
}

?>

Don’t Hard Code WP-Content Directory!

Plugin development tip of the day!
DO NOT HARD CODE wp-content Directory!

I made this mistake not realizing how many people change that directory as a security precaution.

Alternatives

The best alternative is probably the WP_CONTENT_DIR in my opinion. You can also use WP_CONTENT_URL, depending if you want a relative path or a full url.

Examples:
Here is an example of each followed by the output code:
<?php
echo WP_CONTENT_DIR;
echo “<br />“;
echo WP_CONTENT_URL;
echo “<br />“;
?>

/var/www/html/jafty.com/public_html/wp-content
http://jafty.com/wp-content

So now you know!

Want more? Here are some other ways to get similar paths or directories  from within a plugin file:

<?php
echo “<br>”;
echo plugins_url( ‘myscript.js’, __FILE__ );
echo “<br>”;
echo plugins_url();
echo “<br>”;
echo plugin_dir_url(__FILE__) ;
echo “<br>”;
echo plugin_dir_path(__FILE__) ;
echo “<br>”;
echo plugin_basename(__FILE__) ;
?>

The above would output the following lines if it were ran from a plugin on jafty.com:

http://jafty.com/wp-content/plugins/jafty_plugin_tester/test_code/myscript.js

http://jafty.com/wp-content/plugins

http://jafty.com/wp-content/plugins/jafty_plugin_tester/test_code

//var/www/html/jafty.com/public_html/wp-content/plugins/jafty_plugin_tester/test_code/

jafty_plugin_tester/test_code/wp_content_url.php

EDD Instant Updater WordPress Plugin

The EDD Instant Updater WordPress plugin is a plugin I created while working with a custom WordPress plugin that needed to have instant update notifications while using Easy Digital Downloads(EDD). EDD comes with it’s own updater class, but it uses the default WP standards which means you have to wait up to 12 hours after you push an update to get the notice in the WordPress dashboard! With the EDD Instant Updater plugin, you no longer have to wait, the plugin update notices come to you instantly! No more delays!

Interested? Contact Ian L of Jafty.com by email at linian11@yahoo.com for more information.

How to Fix Max File Upload Size on Godaddy and Other Shared hosting Accounts

I ran into this problem using WordPress today where I reached the max upload size on my client’s Godaddy server on a shared hosting account. If you get this error in WordPress, while uploading a file, by the way, it’s probably a max file size issue:

Error: 1

That’s all it said! So it took me a few guesses to figure out what that “Error: 1” message meant.

How to increase the Max File Size Setting in Cpanel

1 – go to your site’s Cpanel by going to yoursite.com/cpanel and log in with the user and password your hosting provider provides for you. You should see this when logged in:

cpanel1

2) scroll down until you see the “Select PHP Version” link in Cpanel that is circled in the below image and click on it:

cpanel1b

3) That will take you to the PHP version selection page. Then click the link in the upper right corner of the page that you see circled in the below image:

cpanel2

4) Clicking the “Switch to PHP Options” link in the above image will take you to a PHP settings page. Look for the upload_max_filesize setting that you see circled in the image below and set it to something higher than 2M according to your individual needs:

cpanel3b

5) After you change it from “2M” to something higher as needed, click the “Apply” button directly to the right of the dropdown and then be sure to also click the “Save” button near the bottom-left of the page as well and then you are done!

PHP WordPress Large background Importer Code

My wonderful client wanted me to add a .CSV importer that imports posts into a Custom Post Type(CPT) in large quantities of around 10k to 50k at a time.

What a standard WordPress site can handle

From my experience building plugins and importers for WordPress over the past 20 years, I have learned to expect trouble if you try to import anything more than 4k to 5k posts into WP at a time. The main requirement for the importer that I am building now is that it is able to import 20k posts in under 15 minutes. Not too difficult, but a challenge none-the-less because the average WP site will timeout after the first 4k posts on average. I also wanted to accomplish this goal without using any bloated PHP Que libraries or Worker Libraries, so I’ll be developing it completely from scratch, just like a grown up!

Step One, Break Large File into Smaller Chunks

The first thing I did while developing my large WP file import feature, was to handle the issue of having a huge .csv file with 20 thousand posts saved in it. What do you do? What I did was wrote a PHP script that reads in that huge file and breaks it up into manageable chunks and saves each chunk to its own separate .csv file. Kind of simple really, this is the easy part!

I created a file named file_split.php to handle this portion of the importer’s code. Here are the contents of that file:

<?php
$chunk_size = 2000;//size of ea. chunk file given in the no. of lines written to the file(excluding the first line with headings that will be at the top of ea. chunk file created).
$max_files = 0;//it will stop after writing this many files, set to 0 for no limmit
$u = $uploadpath;//”double_accounts-test.csv”;
//read a file line by line:
echo “<p>Opening $u to spit it into chunks……</p>”;
$file = fopen($u, “r”) or exit(“Unable to open $u!”);
//extract the first line from the file:
$first_line = fgets($file);
//Output a line of the file until the end is reached:
$i=0;
$ii=0;
$iii=0;
$chunk=$first_line;
while(!feof($file) &&($iii < $max_files||$max_files==0)) {
$i++;
$ii++;
$line = fgets($file);
//echo “$i) $line<br>”;
//add line to lines that get written to files:
$chunk .= $line;
//once we get to chunk_size lines, write a new file
if($ii == $chunk_size){
$iii++;
//echo “<h3>Chunk #$iii:</h3>”;
//echo $chunk;
//create dynamic filenames:
$fn = ABSPATH.”wp-content/plugins/YOUR-PLUGIN/temp/chunk$iii.csv”;
//echo “Writing file $fn….<br>”;
$fh = fopen($fn, ‘w’) or die(“can’t open $fn file to overwrite”);
fwrite($fh, $chunk);
fclose($fh);
$m = “<span style=’color:green’>Chunk Written to $fn</span><br>”;
//reset $ii var back to zero:
$ii = 0;
//empty the $chunk var and add first line to top of file content($chunk)
$chunk=$first_line;
//echo “<hr><span style=’text-align:center;color:orange;font-weight:bold;width:100%;margin-right:111px’>End File #$iii</span>$m<hr>”;
echo $m;
//add the file name to the fnames array:
$fnames[] = $fn;
}//end if $ii = $chunk_size
}
fclose($file);
//if $ii is greater than 0 and less then chunk_size, then there was a left over chunk at the end, so write it to a file too:
if($ii > 0 && $ii < $chunk_size){
$noof_files = $iii+1;
$fn = ABSPATH.”wp-content/plugins/YOUR-PLUGIN/temp/chunk$noof_files.csv”;
echo “Left over chunk of $ii lines remains, so writing it to final file named $fn….<br>”;
//echo “Writing Final file $fn….<br>”;
$fh = fopen($fn, ‘w’) or die(“can’t open $fn file to write final chunk!”);
fwrite($fh, $chunk);
fclose($fh);
echo “<h3 style=’color:green’>FINAL Chunk Written to $fn! DONE chunking $u file! Total files created: $noof_files</h3>”;
//add final file name to fnames array:
$fnames[] = $fn;
}else{
echo “Wow! We broke even with no left over chunk of less than $chunk_size lines, so finished writing files! Final file is $fn.<br>”;
}

?>

Put the file_split.php file up for now. We will include it in another file later when we have the rest of our import feature code written. You can test file_split.php easy enough by

Delete Entire Folder with PHP Code

Today, I had to write a block of pure PHP code to delete an entire folder full of files, sub-folders and more files from a server. This particular job was for a WordPress plugin, but the code I used is not specific to WordPress and can run just fine outside of WordPress or inside a WordPress plugin. The only requirement is an up to date PHP installation for this code to function as intended.

<?php

$path = ABSPATH.’wp-content/plugins/cultivate-crm/test’;
$dir_arr = parse_dir($path);
global $darr;

function parse_dir($path){
static $cntf = 0;
global $darr;
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = “{$path}/{$entry}”;
//Check whether the entry is a file or folder.:
$fof = $entry;
    if($fof != “.” && $fof != “..”) {
    $cntf++;
    $fof = $entry;
    $file_type = filetype($filepath);//get file type.
    $file_size = filesize($filepath);//get file size.
    echo “$cntf) $fof<br />Type: $file_type<br />Size: $file_size<hr />”;
    if($file_type==’dir’){$darr[]=$filepath;parse_dir($filepath);}else{echo “Deleting $filepath….<br>”;unlink($filepath);}
    }//end if is file etc.
}//end while going over files in excel_uploads dir.
}//end parse_dir PHP function by Ian L. of jafty.com

$c = count($darr);
echo “$c empty directories remain…deleting them now….<br />”;
$rdarr = array_reverse($darr);
foreach($rdarr as $dr){
    rmdir($dr);
    echo “Folder $dr deleted!<br />”;
}
//and finally remove the test folder:
$test_folder = ABSPATH.’wp-content/plugins/cultivate-crm/test’;
rmdir($test_folder);
echo “Folder $test_folder deleted!<br /><p style=’color:green’>Now all temporary folders have been removed from the server!</p>”;
?>

Make sure you set your path variable at the top of the script correctly and if you are not in WordPress, replace ABSPATH or set a new PHP constant named ABSPATH and it will work as it is. Since the above code deals with deleting files permanently from the server, I must insist that you use it at your own risk! Be careful because one wrong path entered into this function can destroy your entire file system if you don’t know what you are doing!

MailChimp API 3.0 Helper PHP Function

I’ve been doing a lot of work with the MailChimp API V. 3.0 over the past year while developing the Cultivate CRM WordPress Plugin and I created the following helper function that has made live a lot easier for me since I have to make probably a dozen calls to the API within this one plugin.

MailChimp API 3.0 Helper Function

<?php
function mailchimp_request($mcAPIkey,$url,$req_type,$json=''){
//send a HTTP POST, GET or PUT request with curl:
 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $mcAPIkey);
 curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_TIMEOUT, 100);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req_type);//GET, PUT, POST
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 if($req_type!="GET")curl_setopt($ch, CURLOPT_POSTFIELDS, $json);//not needed for GET requests
 $result = curl_exec($ch);
 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 curl_close($ch);
 // echo "http code: $httpCode<br />";

$body = json_decode($result);
 //echo "successfully got list for Cultivate CRM!<br />result:<hr />$result<hr />";
 $results['code'] = $httpCode ;
 $results['result'] = $result;
 // store the status message based on response code
 if ($httpCode == 200) {//if no error occurred:
 return $results;
 } else {//else an error occurred:
 return false;
 }//end else an error occurred
 }//end mailchimp_request PHP function by Ian L. of Jafty.com

Calling mailchimp_request Function

Here is how you use the above mailchimp_request PHP function:

<?php
//Construct the MailChimp API URL:
$mcAPIkey = 'YOUR-MC-API-KEY';
$mcListID = 'YOUR-MC-LIST-ID';
$email= 'MEMBER_EMAIL@EMAIL.COM';
$memberID = md5(strtolower($email));
$dataCenter = substr($mcAPIkey,strpos($mcAPIkey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $mcListID . '/merge-fields/';    
//get the response:
$response = mailchimp_request($mcAPIkey,$url,'GET');
$httpcode = $response['code'];
$result = $response['result'];
$decoded_result = json_decode($result);
echo "http code: $httpcode<br>";
echo "Response data from getting address field data from MC API:
";
$merged_field_obj = $decoded_result->merge_fields;//should be an array of merged fields
print_r($merged_field_obj);
?>

WordPress Plugin Admin Page Unwanted Scroll

I was working on a custom plugin for an important client today and one of the plugin’s admin pages would scroll half way down the page every time I landed on it and I couldn’t figure out why at first!

Long story short, I found out what was causing it was an inline JavaScript block of code, so If anyone has this issue in a WordPress admin page while making a plugin, try getting rid of the JavaScript and it should stop the page from scrolling as it did in my case.

If you experience something similar, please mention how you solved it in the comments.

MailChimp API

I’ve been doing a lot of work with the MailChimp API lately and figured it would be good to have a page dedicated to it here for future reference because it’s not very well documented online anywhere else… Hoping this will help some people who also have to use MailChimp’s API.

Understanding MailChimp Lists and the API

If you’ve ever dealt with MailChimp, you know that it is based on lists which can be segmented, grouped and managed all from the API as needed. Next I will demonstrate how to get a list of MailChimp lists and information on each list that exists.

Getting MailChimp List Information from API

Here’s the code I created to get all MailChimp Lists and information on each list from the MailChimp API using PHP code:

<h2>MailChimp List Info:</h2>
<?php
//Get API key :

$mcAPIkey =’Enter_your_own_API_key_HERE’;
//get info regarding MC lists
//use following url ‘https://usX.api.mailchimp.com/3.0/lists’

$dc = substr( $mcAPIkey, strpos( $mcAPIkey, ‘-‘ ) + 1 ); // datacenter, it is the part of your api key – us5, us8 etc
$args = array(
     ‘headers’ => array(
        ‘Authorization’ => ‘Basic ‘ . base64_encode( ‘user:’. $mcAPIkey )
    )
);

$response = wp_remote_get( ‘https://’.$dc.’.api.mailchimp.com/3.0/lists/’, $args );
$body = json_decode(wp_remote_retrieve_body($response));

$rcode = wp_remote_retrieve_response_code($response);
$tot_itms = $body->total_items;
echo “Response code was $rcode …$tot_itms items found!<br /><hr />”;
echo “<pre><code>”;
print_r($body);
echo “</code></pre><hr />”;
?>

The above code would return something like this for a MailChimp account that has one saved list:

MailChimp List Info:

Response code was 200 …1 items found!


stdClass Object
(
    [lists] => Array
        (
            [0] => stdClass Object
                (
                    [id] => xxxxxxxxx
                    [web_id] => xxxxxx
                    [name] => List Name
                    [contact] => stdClass Object
                        (
                            [company] => Company Name
                            [address1] => 1001 Your Road
                            [address2] => 
                            [city] => Adolphus
                            [state] => KY
                            [zip] => 42120
                            [country] => US
                            [phone] => 
                        )

                    [permission_reminder] => You signed up to learn more about how our team can better serve you.
                    [use_archive_bar] => 1
                    [campaign_defaults] => stdClass Object
                        (
                            [from_name] => First Last
                            [from_email] => your_email@domain.com
                            [subject] => 
                            [language] => en
                        )

                    [notify_on_subscribe] => 
                    [notify_on_unsubscribe] => 
                    [date_created] => 2018-02-25T02:01:38+00:00
                    [list_rating] => 0
                    [email_type_option] => 
                    [subscribe_url_short] => http://eepurl.com/dBXF4r
                    [subscribe_url_long] => https://yourcompany.us13.list-manage.com/subscribe?u=bf405c1xxxxxxxxb48df64c3&id=xxxxxxxxxx
                    [beamer_address] => us13-5df785xxxxx-xxx@inbound.mailchimp.com
                    [visibility] => pub
                    [double_optin] => 1
                    [marketing_permissions] => 
                    [modules] => Array
                        (
                        )

                    [stats] => stdClass Object
                        (
                            [member_count] => 3
                            [unsubscribe_count] => 0
                            [cleaned_count] => 0
                            [member_count_since_send] => 5
                            [unsubscribe_count_since_send] => 0
                            [cleaned_count_since_send] => 0
                            [campaign_count] => 2
                            [campaign_last_sent] => 
                            [merge_field_count] => 4
                            [avg_sub_rate] => 1
                            [avg_unsub_rate] => 0
                            [target_sub_rate] => 0
                            [open_rate] => 0
                            [click_rate] => 0
                            [last_sub_date] => 2018-04-28T20:26:38+00:00
                            [last_unsub_date] => 
                        )

                    [_links] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [rel] => self
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/edxxxxxxxxx
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Response.json
                                )

                            [1] => stdClass Object
                                (
                                    [rel] => parent
                                    [href] => https://us13.api.mailchimp.com/3.0/lists
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists.json
                                )

                            [2] => stdClass Object
                                (
                                    [rel] => update
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/edxxxxxxxxx
                                    [method] => PATCH
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Response.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/PATCH.json
                                )

                            [3] => stdClass Object
                                (
                                    [rel] => batch-sub-unsub-members
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxxx
                                    [method] => POST
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/BatchPOST-Response.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/BatchPOST.json
                                )

                            [4] => stdClass Object
                                (
                                    [rel] => delete
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxxxxx
                                    [method] => DELETE
                                )

                            [5] => stdClass Object
                                (
                                    [rel] => abuse-reports
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxx/abuse-reports
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Abuse/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/Abuse.json
                                )

                            [6] => stdClass Object
                                (
                                    [rel] => activity
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxx/activity
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Activity/Response.json
                                )

                            [7] => stdClass Object
                                (
                                    [rel] => clients
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxxxxxx/clients
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Clients/Response.json
                                )

                            [8] => stdClass Object
                                (
                                    [rel] => growth-history
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxxxxxxxxx/growth-history
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Growth/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/Growth.json
                                )

                            [9] => stdClass Object
                                (
                                    [rel] => interest-categories
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxxx/interest-categories
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/InterestCategories/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/InterestCategories.json
                                )

                            [10] => stdClass Object
                                (
                                    [rel] => members
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxx/members
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/Members.json
                                )

                            [11] => stdClass Object
                                (
                                    [rel] => merge-fields
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxxx/merge-fields
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/MergeFields/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/MergeFields.json
                                )

                            [12] => stdClass Object
                                (
                                    [rel] => segments
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxxxxx/segments
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Segments/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/Segments.json
                                )

                            [13] => stdClass Object
                                (
                                    [rel] => webhooks
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxx/webhooks
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Webhooks/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/Webhooks.json
                                )

                            [14] => stdClass Object
                                (
                                    [rel] => signup-forms
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxxxxx/signup-forms
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/SignupForms/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/SignupForms.json
                                )

                            [15] => stdClass Object
                                (
                                    [rel] => locations
                                    [href] => https://us13.api.mailchimp.com/3.0/lists/xxxxxxxxxxx/locations
                                    [method] => GET
                                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Locations/CollectionResponse.json
                                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/Locations.json
                                )

                        )

                )

        )

    [total_items] => 1
    [_links] => Array
        (
            [0] => stdClass Object
                (
                    [rel] => self
                    [href] => https://us13.api.mailchimp.com/3.0/lists
                    [method] => GET
                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/CollectionResponse.json
                    [schema] => https://us13.api.mailchimp.com/schema/3.0/CollectionLinks/Lists.json
                )

            [1] => stdClass Object
                (
                    [rel] => parent
                    [href] => https://us13.api.mailchimp.com/3.0/
                    [method] => GET
                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Root/Response.json
                )

            [2] => stdClass Object
                (
                    [rel] => create
                    [href] => https://us13.api.mailchimp.com/3.0/lists
                    [method] => POST
                    [targetSchema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/Response.json
                    [schema] => https://us13.api.mailchimp.com/schema/3.0/Definitions/Lists/POST.json
                )

        )

)