How to use JSONP (AJAX to SSL) in WordPress, an EASIER way

I’ve already written about How to use JSONP in WordPress Development. I explain how it works, and why you would use it there.

At work we work with several domains and I’ve had to use quite a bit of JSONP, I’ve rethought how to use it, and made this micro-framework to make it a LOT easier. Mostly, I wrote this to solve the problem that I’m using a lot of AJAX, and don’t want the overhead of the .ajax call each time.

There are a lot of values you need to set when making a JSONP call in general, and specifically with WordPress, this greases those wheels.

The paradigm is all you do is execute:

wp_jsonp("wp_jsonp", "getStuff", {variable: "hello world"}, getStuff);

and the rest is taken care of on the JS side. I wrote it to be agnostic of the server-side processing as well, this gives you the benefit of a pseudo factory design pattern with your switch statement.

You can download the whole repo to peruse or play with if you like, I made some gists for easy embedding.

This is the guts of the operation, I created this javascript object that handles everything, you past the ajax event, method, parameters and a callback function. The plugin takes care of the nitty gritty details that are a pain to remember for getting jsonp to work.

It’s well commented, so read through and feel free to ask questions in the comments if you have any.

Here’s the example, you might say, wait a minute, don’t you get a callback from jQuery already? Sure, good luck using it. It’s a little funny ignoring that, but hey, this works nicely.

Maybe I’m overthinking / over-complicating things, I don’t know, once it’s set up you can move really quickly, isn’t that the point of a framework?

Just one important note: make sure to validate the hell out of things because you’re giving that JS function a LOT of power.

I’d love to hear your thoughts, if you have suggestions for improving it, by all means, please comment below!

How to recursively make a directory (folder) with PHP

When I need to generate or save files in a web application it’s important that I keep all the files in an orderly fashion.

Sometimes I think that there’s a fine line between impressionistic and messy.
Lady Gaga

Here’s the go-to code I use to generate the directory structure.

You can find more solution on this StackOverflow thread.

How it works

is_dir() is a native PHP function that will say if a relative path is given is a directory or not. If the path doesn’t exist, it will return false.

|| – is the OR operator in PHP. If the path is a directory exists the function will return without moving over to the second part, because we’re saying do this OR that.

mkdir() is a native PHP function that will create a directory at the path location that is given.

The parameter $path is the path where the directory should be created.

The parameter $permissions is the chmod() settings of directory being created.

The ‘true’ creates the directory recursively. This means that you only need to create the path, and you don’t need to make sure the whole path exists. It will fill in the gaps.

Why not just use mkdir() by itself?

You can, but if you do, and the directory already exists, it will send out an error to the log. Nothing terrible with that, I just like keeping things clean.

If you feel that this site is running snappier, you’re probably right.

I went to 3 meetups this week:, WPNYC, and Web Performance NY.

At two of them people mentioned Percona. So I thought I’d check it out. Digital Ocean has a great tutorial if you’d like to check it out: How To Install a Fresh Percona Server or Replace MySQL. I got stuck for a bit, but found a solution deep in the comments of a StackOverflow answer. It turns out that when I removed MySQL to install Percona it removed the php5-mysql module.

Before installing it commando on my personal site, I tried it first in my dev box at work and got a 5x improvement in speed.

This is not a scientific experiment, I implemented two other improvements as well:

  • Switched from W3 Total Cache to WP Super Cache.
  • Expanded my Digital Ocean instance as Percona recommends 1GB RAM.

Hope this helps you’re reading experience at my digital home.


How to use JSONP in WordPress Development. The Quick-and-Dirty QuickStart Guide

Edit: Looking for an easier way to do JSONP in WordPress?

What IS JSONP and why should I care?

There’s been a lot of debate lately about whether to move your site to SLL (https) or not. It’s clear, though, that all your forms, at least the ones that handle sensitive data like logins, should go over a secure connection.

If your whole site is SSL then you won’t have any issues with making AJAX calls; however, if you DO go hybrid then Javascript will consider all the pages that are SSL as a separate domain and will block AJAX calls to them.

Use case: You want to secure your admin area and you add define(‘FORCE_SSL_ADMIN’, true) to your wp-config.php file. You’ll remember that to make AJAX calls in WordPress you need to call: “/wp-admin/admin-ajax.php.” But that will now be an SSL connection and violates Javascript’s “same-origin policy“.

This is where JSONP comes into the picture. As you probably know, you CAN include scripts from other sites using a script tag, that ability is the foundation of CDNs. JSONP takes advantage of that functionality.

Basically, instead of including a static script on your site hosted on a  CDN, you’re sending a GET request to the domain of choice, and asking it to send back a callback method including within it a JSON object with the data you want. In essence, you’re spoofing your browser to think that it’s not actually doing a cross-domain ajax call, but in practice, you are.

There’s a great discussion on StackOverflow about JSONP for further exploration.

How do I do it?

Below you’ll find two files, upload them to a folder in your WordPress plugins directory and activate. Note: you should probably run this on a test site. It won’t do anything bad to your site, but it’s never a good idea to play around on your production site.

To test it add the following to any page:

<input name="title" type="text" /> <input name="titleSubmit" type="button" />

The javascript looks for an input button, on ANY page of your site, with the name “titleSubmit” and does the JSONP call with the content of an input text field on that page with the name of “title”.

The most important pieces in the example that you’ll need to get your code running are:

In the js file:

Clearly without any of the code it won’t work properly; however, the above settings are not typical of most of your standard AJAX calls.

type: GET: By it’s very nature a JSONP call cannot be POST. You’re essentially embedding a script tag on your page with GET variables in the URL of the script.

cache: false: Removing this will not break your code, but for testing it’s best if you your browser doesn’t cache the responses.

dataType: “jsonp”: You’re telling jQuery that it’s a JSONP call. Duh.

crossDomain: true: Perhaps with the dataType set to JSONP you’d think the that this would be enabled, that’s the whole point, but you still need to set this.

In the PHP file:

content-type: text/javascript: You’re setting the response type being sent, application/javascript will work as well.

access-control-allow-origin: *: This is another security check, you need to enable any origin for JSONP to work.

$_GET[‘callback’]: Without the callback wrapping your JSON response jQuery will not recognize this as a valid response. It is set in place as a security measure similar to NONCEs.


Once you have the right recipe, JSONP with WordPress is not all that difficult. Use it well.

As always, questions? comments? Don’t hesitate to do so below.

Why I went to the cloud…

I was asked to write a blogpost about my server setup. Specifically, about “the best fixes for wrangling all of those crazy cables.” To which I responded: “Oh, I just use the cloud. Never used anything else.”

Why don’t I host my own physical server? Cold hard cash. For the level of scale I need, a few hundred hits a day, it would be overkill to buy my own.

That question got me thinking about why I do wrangle my own server, albeit in the cloud, instead of relying on hosted solutions. So here goes…

I’ve used many of the popular shared, and not shared, hosting solutions. But I’ve always come across the same issues. As my development skills improve, I find that I can only do less and less with what I have, when I rely on others for the environment in which I run my site.

Let’s say I need to increase the upload limit in your php.ini? NOPE!

Do I want to install git? Wait, I can just install that from the command line?! What else does my unix user have permissions to do? …or other users for that matter…

Wait, you aren’t running PHP 5? Ok, I get that it’s complicated to upgrade PHP for existing users because you don’t want to break their sites, but, c’mon! I’m a new user!!!

Through a mixture of horror and frustration I decided to look into alternatives. But, to be honest, I was afraid of running and configuring a server of my very own.

For my first attempt I tried SUSE linux; because that’s what was being used at the office at time. But I really couldn’t keep it running. It just kept restarting. I didn’t know enough then to be able to say even now why that happened.

But I persisted experimenting, and with some shameless begging, we switched to CentOS in the office. I took that opportunity to build my own development environment locally. Around the time I started feeling comfortable with playing around with server configuration I discovered DigitalOcean.

After playing with AWS for a bit, moving to DO felt like moving to Apple from Windows XP. I had to give up a few controls that I didn’t feel too strong about, in exchange I didn’t have to think too much about settings I don’t care about. The server just worked. No extra services were needed and I knew the cost.

So to answer the question of why I wrangle my own server?

First, I like understanding the technologies upon which I am relying. The more you understand, the better performance you can pull out of something — “full-stack development” should include the Linux/Apache (or Nginx) part of the stack.

Second, I you’re building an plugin or theme for distribution you need to make sure it will be compatible, and you can’t really rely on the masses to be running any advanced server setups. So don’t bother with anonymous PHP functions. But if you’re building something for yourself, you should be able to enjoy the benefits of PHP 5.5 and more.

I’m currently working on version 3 of my server. I just moved from CentOS with a traditional Apache, PHP setup to Ubuntu with Nginx and PHP-FPM.


Well, first of all, all the cool kids are doing it.

More importantly, Apache slows down under heavy load, because of the need to spawn new processes, while Nginx was designed specifically to handle high traffic sites. In addition, PHP-FPM runs along side the webserver, instead of on top — like a traditional setup with apache — which reduces the recourses available.

This is a great example of the first reason I stated above. I saw a relatively easy way to improve my site’s performance. Since I’m in control, I can do it.

Setting up an Ubuntu Desktop LAMP development server

So you’ve inherited a WordPress site and you want to start developing for it. But you don’t want to go commando on the production site. Smart.

How do you set up a local development environment?

In this tutorial I’ll walk you through setting up a simple dev environment on Ubuntu desktop.

WordPress typically runs off a LAMP stack. Not always, but most sites do. So that’s what we’ll set up.

LAMP stands for:
L inux – the operating system. In this case Ubuntu.
A pache – the web server. Sometimes Nginx is used.
M ySQL – the database.
P HP – the server-side scripting language.

The first step is to make sure you’re completely up to date.

So let’s open up the terminal and run:

sudo apt-get update

Now we install the lamp server, run:

sudo apt-get install lamp-server^

Since Ubuntu 10 there’s this. Pretty easy, right?

Type your password. Agree to the packages it’ll install. This will install ALL of the modules and packages you’ll need to run a web server locally.

You’ll get a prompt to set a password for the root user for MySQL. Even though this is local, it’s best to keep to best practices, so don’t just press enter.

That was ridiculously easy. Let’s test that by going to http://localhost/ in the browser. You should get a success apache screen.

Let’s test PHP:

sudo touch /var/www/html/info.php

sudo nano /var/www/html/info.php


<?php phpinfo();&#91;/prettify&#93;

Ctrl C to exit.

Then navigate to: <a href="http://localhost/info.php">http://localhost/info.php</a>
You should see the phpinfo screen.
Also to keep with best practices, once that&#8217;s done run:
[prettify]sudo /usr/bin/mysql_secure_installation

Remember that password we just set? You’ll need it now.
No, you don’t need to change the password you just set.
Say yes to the rest.

Next we’ll need a database for WordPress to use. So type:

mysql -u root -p

Enter the password you set for root.

Then create the database:

create database wordpress;

Then: exit

Now we’re almost ready to install WordPress, we just have to deal with some permissions, so we can code comfortably.

First, we’ll need to grant apache access to the html directory:

sudo chown -R www-data:www-data /var/www/.

Then we need to add ourselves to apache’s group:

sudo usermod -a -G www-data YOURUSERNAME

In order for that to take effect, you’ll have to log out and log back in.

Now, we still can’t do anything in the html directory. That’s because we need to grant read/write/execute permissions for the apache group.

sudo chmod -R 775 /var/www/.

And Viola! WordPress time!


Let’s extract that to: /var/www/html/

If you go to http://localhost/wordpress in your browser you should see the installation wizard.

Click “Create a Configuration File” then “Let’s go!”

The “Database Name” keep as ‘wordpress’, we just created that.
“User Name” is ‘root’.
“Password” is whatever you set for that.
“Database Host” keep as ‘localhost’.

Usually it’s not a good practice to keep the root user for running your applications, but for expediency we’ll keep it for now.


Aaannnd this: “Sorry, but I can’t write the wp-config.php file.”

No problem. Click back in your browser, and go back to the terminal. Run:

sudo chown -R www-data:www-data /var/www/.

Again, and we’ll resubmit. Because we copied the WordPress files apache didn’t own that directory. You should be good to go now.

“Run the Install”

Fill out the form. And we can log in now!

Congratulations! You now have your own development server running off your Ubuntu desktop.

Let’s test that out… Yup, all seems to be working just fine.

This site you can now develop for and break with impunity.


I’m proud to announce the launch of the author site of my talented wife: Ilana C. Myer.

The art is by the very talented Galen Dara; the site design and development is my own. I wanted to take a few words and go a bit into my thoughts behind that design.

The design: The primary purpose of the site is for Ilana to share updates and insights about her upcoming book.

Towards that goal, it was important for me was to have a beautiful readable type. I used Calluna. It has an elegant feel. What struck me about it was the elegance of the serifs, and how it balanced that detail with a clean reading experience. 

To balance out the serif body type I used Lato I believe that it was intended to be used as a thinner sans-serif. However, for contrast I used it’s thickest weight. I think it still works nicely.

For Ilana’s name, at the top, we used Neue Hammer Unziale. It’s Celtic look was apropos due to the influences of the book. (You’ll just have to read it to find out more.)

Having commissioned the art, we wanted to put it front-and-center. I felt it would immediately place the visitor into the world of the book. Thankfully, the visual trend now is leaning towards full screen hero images.

The transparent heading before the posts on the homepage is to keep the visitor inside that world, always reminding them of the art. The art can be seen in full by scrolling all the way to the bottom.

The page heading recluses itself as the visitor scrolls down to bring the visitor into the text, reducing the distraction of the art.

The tech: I used underscores as a base theme and set up a grunt watch to compile my LESS and JS files. Nothing too fancy; not much needed for a blog.

Demystifying the WordPress Plugin

I asked one of the guys on my team to build a WordPress plugin, he balked. I realized that he just didn’t get how easy it is. So I thought I’d dedicate some time to dispelling the myth that plugins are complicated to write. “Plugin” sounds formidable. But really, a plugin is a file in the plugins directory with a comment. That’s it. To build your first plugin create a file, name it whatever you like, and place the following code at the top:

Go to your plugins menu and you’ll see your shiny new plugin there.

What do you put in there besides the comment? Typically, anything you’d put in your theme’s functions.php file. Unlike with the functions.php file which runs everything you put in it, where plugins are concerned you can decide whether to “activate” the code or not.

Here’s a great post with 25+ potential plugins. Let’s try #3 (Don’t forget to change the plugin’s name):

SharePulse Relaunched

I am happy to announce the relaunch of SharePulse. (From the site)

Relying on hit counts simply does not reflect the impact of your posts. SharePulse finds and ranks your site’s posts that have the greatest social impact. The stats are gathered from Twitter, LinkedIn, Facebook as well as your own site’s most commented posts measuring actual engagement. SharePulse lets you display these posts in your site’s sidebar showing off your posts which have had the greatest social impact over the past day, week, month year or for all time. Each post is displayed with the total number of tweets, shares and comments.

This version was rebuilt from the ground up. It now uses more reliable stat counters and was built lean and with stability in mind. While it’s version 3, it is in alpha. It’s stable enough for a production server, but I decided to tag it as “incomplete” because of all the features I have planned.

So please, use it on your site, enjoy it! And I’d love your feedback.

Database Indices

I recently had the pleasure of indexing our company’s sites’ tables. The  custom CMS I inherited has some really brilliant code, but it also has quite a large amount of idiotic code blocks as well. In this case, the database was not thought out as best it could have.

I was able to reduce some ridiculously long queries from 10 seconds down to 2 seconds with a few well placed indices. While 2 seconds isn’t anything to brag about. It’s quite an improvement. A database index is a lookup table that is created to help query information more quickly.

Before jumping in. One thing to note about indices is that there is an expense. If you go ahead and index your entire table it will likely take longer to run that query than a non-indexed table. So you have to be discerning about what you index.

The rule of thumb is, anything that alters the query, typically a WHERE clause or ORDER or GROUP, is a potential candidate for an index. For me, the rest of the process was trial and error, I went through all the potential candidates in my longest queries and tried various combinations until I came up with the quickest time for each query. There may be an algorithm for calculating the best columns to index. But this worked.

phpMyAdmin doesn’t make it easy to find your indices.

( Don’t get any funny ideas, this is just a typical WordPress install. )

1) Open a table, click “Structure” at the top.

where are you?

2) At the bottom of the page is a tiny link that says “Indexes”. You can manage existing indices from here.

oh there you are

3) To add an index check to see if there’s a “More” menu on the column you’d like to index…

and how do I do that?