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 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.

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

type: <?php phpinfo();

Ctrl C to exit.

Then navigate to: http://localhost/info.php

You should see the phpinfo screen.

Also to keep with best practices, once that’s done run:

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.

Obamacare Websites “Irresponsibly” Built on WordPress

Edit: Just wanted to point out. According to the video below, if you go here you can hack ALL OF WordPress! How irresponsible?! Oh yeah, and you can hack Google here.

I’m a fan of TWIT, I listen to the show weekly–it’s one of my favorite podcasts, in fact. I like it because Leo Laporte is clearly very smart, is knowledgable about tech, and he lands outstanding guests. The clip above, though, is a perfect example of how intelligent people can be wrong.

“This is the federal one, is also running on WordPress. (laughs)”

Why wouldn’t it? He really doesn’t explain what issue he has with WordPress, except that you can go to /wp-login.php to get to a login screen. As of writing this post there are over 70 million sites running WordPress. Among them are NBC, TED, TechCrunch, CNN, Time, Dow Jones, and UPS, which are running off WordPress VIP, among many other high-profile sites. WordPress is an elegant platform upon which you can build pretty much anything. In fact, more people are using WordPress as the infrastructure for a web application than they are for purely a blogging engine.

“Of those who use WordPress, 69% use it only as a CMS (Content Management System); 20% use it as a blog/CMS combo; 6% use it for blogging only; and 7% as an application platform”

– State of the Word 2013, statistics

So there really is no problem with building your site, even if you are a government health exchange, on top of WordPress. The real problem is who is building that site. I was at a party recently and was shmoozing with a fellow developer who mentioned that his company was forced to use a contractor to build their site. My partner burst out laughing when he said that because of my expressive reaction. Web contractors are notorious for building shoddy sites. I’m not saying every contracted site will be poorly built, but their job is to get the site done and move along, which is not conducive towards quality. Not to mention that a good site is a site that is maintained. Consequently. That is exactly why you should have your site built in WordPress. Whether your site is built in-house, or your site is being contracted, I highly recommend building it off WordPress. WordPress is constantly being developed by a quality open-source community. Open source means that everyone and anyone can dig in and read the code. Sounds a little scary, right? But this actually makes WordPress more secure. I read the WordPress source code for fun in my spare time, I learn a lot that way, and countless other expert developers do the same. When ways to improve are found, they’re included into the next release. If and when security holes are found, patches are released to the community immediately. Can you say that for YOUR site’s infrastructure? If your site is a proprietary site, or maintained by a small team, you can’t say the same. WordPress has been tested by 19% of the internet. If security holes were found regularly, you’d hear about it.

A good site is a site that is maintained.

Building off WordPress you can rest assured that your site’s engine will continue to be developed long after your developer has left. YES, your site’s custom theme and plugins will need updating. But that will cost you MUCH less than it would to have a whole new site built. As to the security concerns Leo and his esteemed guests raise. Many developers aren’t aware of all that is needed to properly secure a website,WordPress or not. Especially if your developer is looking over the horizon towards their next gig, being a contractor and all. If you’re concerned about your WordPress site’s security, go ahead and harden your site  right now.

How to Use AJAX in WordPress Development. The Quick-and-Dirty QuickStart Guide

Edit: Enjoyed this? Check out my new post on AJAX using JSONP in WordPress.

There are some great posts and a fantastic wiki page explaining how to use AJAX in WordPress. But I haven’t found a quick plug-and-play tutorial. So here goes…

The problem: A simple form that will give the visitor an input and when they click “Next” it will send the content of the input to the server who will send all the $_POST fields back as JSON. Why you’d want this? Who knows. But it’s a simple problem to solve that you can adopt to do anything.

Here’s the Gist

This is the plug-and-play version my friends. (Extra points if you recognize what ui framework is here… DON’T JUDGE ME IT’S ONLY FOR WIREFRAMING.)

How to use the code

  • Add include_once('inputtitle_submit_inc.php'); in functions.php. Make sure inputtitle_submit_inc.php in in your template folder.
  • page-ajax_input.php is a template page, make sure it’s in in your template folder. Just create a page in WordPress using “Input Submition Page”.
  • inputtitle_submit.js should be in a folder named ‘js’ in your template folder. Otherwise

wp_enqueue_script( 'inputtitle_submit', get_template_directory_uri() . '/js/inputtitle_submit.js', array( 'jquery' ));

will fail.

How it works


This is a simple template file. The important elements here are the input field and the next button. They are hooked in the JS file.


The server-side magic.

The first line enqueues the js file and pops some variables in for the AJAX onto the page. They are called in inputtitle_submit_scripts().

The next two lines enable the AJAX to work. They create the ajax action “ajax-inputtitleSubmit”. If you only have “wp_ajax_ajax-inputtitleSubmit” it will only work for logged in users. If you only have “wp_ajax_nopriv_ajax-inputtitleSubmit” it will only work for logged out users. If you do this, make sure you have serious security in place.

Those two lines tie the action to myajax_inputtitleSubmit_func(). This is what happens server side. Inside you’ll find some nonce magic for security. The function checks the nonce, then converts the $_POST variables to JSON and sends them back to the browser. Don’t forget the exit();


The Javascript.

First I encapsulate the JQuery so that it won’t conflict with anything. Then when the DOM is ready…

When “Next” is clicked it sends a POST AJAX request to the server. The AJAX URL was defined in wp_localize_script in inputtitle_submit_inc.php as well as the nonce.

We send the action, the nonce and the inputted “title” as variables to the server. Then in outputs the response (all $_POST variables as JSON) in the console.


I built this for reference sake. If you can suggest any best practices or improvements please comment below.

WordPress postmeta is useful, but be careful

The add_post_meta, delete_post_meta, update_post_meta, and get_post_meta functions are really useful. It’s the perfect place to store information about a post. Many plugins take advantage of this storage for determining whether a specific post/page needs the feature they are providing or not.

Example: I recently installed on a site I manage the WordPress HTTPS plugin; it allows you to force SSL on a specific page or post of your site.

Once enabling the plugin on a page on the site I checked the “Custom Fields” section (where the postmeta fields are displayed on the post edit page) and lo and behold:

Screen Shot 2013-02-03 at 5.27.49 PM

A new postmeta field had been added.

Not surprising, as I said, it’s a useful place to store information. But there is one aspect of this feature you should be aware of: it is cached on page load.

When you run the WordPress loop many wonderful things happen to make your page load as efficiently as possible. One of those things is that WordPress caches all the postmeta values when it loads the post.

This means two things:

  1. You DON’T have to worry about the amount of times you call the same value through get_post_meta(), since your server is not making a new query for each function call.

  2. You DO have to worry about how much information you are storing in the postmeta since all that information will be loaded into server memory each time the post or page is loaded. Normal storage will work fine, store things like settings, variables and content that is needed for displaying the post. But don’t think about the postmeta as a place for unlimited storage. Some things do need their own table.

What do I mean?
In short, don’t store post logs or large amounts of stats and data there.

Example: I made a file uploading plugin for a client to be used internally in their company, that leverages plupload built into WordPress. I tied the backend into the company’s LDAP server so that any org member could sign into the uplaoder and not need an account created. Each file uploaded was tied to the user’s account so that they could each manage their own files. There’s a few more useful features thrown in like: file expirations, secured files, and dynamic file serving. I’ll be happy to post specs at some point. It’s pretty cool.

One feature I added was logging file access. So that when each file is accessed there is a trace of who/what/where/when. I thought: “what better place to store that information then in the postmeta?” Right? NOPE. The site ran smoothly until images uploaded were used in an email blast. The blast only went out to a few thousand people, but each time any of those images were loaded i.e. each email opened, the ENTIRE access log was loaded into the memory.


'update_post_meta_cache' => false

Was the quick fix, and gave me time to offload the logs and refactor the code…

For more information about the power of the Loop I highly recommend watching Andrew Nacin’s talk about WP_Query, talk slides.

Why Automattic Should Buy Path

Alternate Title: How WordPress Can Fix Social

I went to the breakout NYC PandoMonthly Event this by Pando Daily past week. It was a pleasure watching Sarah Lacy (@sarahcuda), doing what she does best: interviewing one of my heroes Matt Mullenweg (@photomatt) all about WordPress, how he got started, the future of WP, social networks and distributed work environments.

During the conversation, which I recommend y’all watch as soon as it’s posted, Matt discussed how WordPress has only skimmed the surface of social, and how the little they’ve tried has reaped 40x normal engagement.

I first heard about Path from Jason Calacanis (@jason) on TWiST and then several months later when he was talking about how people don’t trust Facebook anymore. He said that he trusts Path and that means a lot to me but honestly, who wants to sign up for yet another social network? I usually am an early adopter of tools and services, I like exploring new ideas. But… another… social… network? I finally tried it out because the rockin’ Noni Cavaliere (@missversatile) told me that I have to.

Path ROCKS in many many ways. It has a beautiful interface. It’s really really easy to use. And it lets you pass your post on, frictionlessly, to any of the other rockstar networks you’d want to share with. The idea is that you add to your Path network your close friends and family — the people you want to share your life with — and if there are some things you want to share further, it’s really easy to do.

This solves one of the adoption issues. Because of its beautiful interface, you want to share things, and since you can share to all the places you’d want to share to, it becomes your go-to app for social sharing.

My problem with Path is, ultimately, that you have to trust it in the end.

When I started with Facebook it was the perfect walled garden. I could share my life on it without worrying about being judged. Sure, whatever you put online you have to monitor, but Facebook today makes you feel like a product. Bacteria in a petri dish, where their scientists throw all sorts of things at us to see what we osmose. That’s their business model. We are the product, marketers are the clients, and Facebook sells our information to them. Ultimately, you’re just a number to everyone… but it still makes me feel… Icky. Things on Facebook may look peachy but are they really?

And that’s the problem with Path. Here’s a scenario: Path takes off, everyone adopts it. Then the VCs come in and say: “How will you monetize?” Then Path goes to milk its greatest asset… Us. Again. So why would I want to go through that all over again?

The space in social that is wide open for the taking is the safe social space.

I want to own my own content. I want to know that I can hide it, take it down, delete it, do whatever the fuck I want with it… because my life is MINE. And I don’t want anyone else owning it, using it in ads, selling it, without my explicit knowledge and control. I don’t want my privacy settings changed behind my back and if I wanted to be posted in ads all over the place I would have become a model. There isn’t real privacy today. And maybe that’s a problem.

This, I really truly hope, is why the centralized social networks will die eventually.

Diaspora had the right idea. They did a great job jumping on a wave of privacy discontent. What they got wrong was ease-of-adoption. Only a hacker can really use it in its full de-centralized glory.

WordPress understands user trust. They are about as transparent as you can get. Anyone can dig into the codebase and see exactly what they’re doing with your information. At any time you can export your account  and spin your own self-hosted flavor…. and BOOM! You’re in complete control. Even Jetpack, the new integration of tools between the self-hosted flavor and hosted site, is a plugin that you can open up and dissect.

The ideal social network needs to work like this. Which is why Automattic — the company — should buy Path.

The ideal social network would give you the ease-of-use and ease-of-adoption of Path, with the transparency and control of WordPress. Even the concept that Path sells — Path should provide you with the simple way to keep a journal, or “Path,” of your life on the go. — fits perfectly with the WordPress model… and is ultimately what I want my personal private blog to be.

…and if Automattic doesn’t feel like buying Path, perchance Path will consider building a spinoff platform on WordPress that hooks into the Path network…

As always, I love your input. Please comment below and let me know what you think.

Responsive Design – WordPress NYC

In case you missed it, there were 60 people on the waiting list… Here’s the talk I gave at WPNYC in April about Responsive Web Design.

I spliced out my piece from the full video, but if you’d like what you see here, Sonja did a great job canvasing the Responsive Design conversation.

My talk covered the following:

The Pros and cons of Responsive Design

  • What people are saying about Responsive Design. Is it right for you?

Progressive Enhancement vs Graceful Degradation

  • The essence of Adaptive Design: If you want to use the cool stuff, build it up right so you don’t shoot yourself in the foot.

Implementing Adaptive Theme Design

  • Concrete steps you can take to make your theme Adaptive.
You can follow along with the talk slides as well… (Ironically, best viewed in Safari)

As always, I love your input. Please comment below and let me know what you think.


April WPNYC: Responsive Web Design

I had the privilege Tuesday night of speaking to some of the greatest WordPressers in the world at the Official WordPress New York Meetup. It was a true honor.

If you missed the performance or  would like to review the slides, feel free!

View The Presentation I gave on Adaptive Web Design

Use keyboard arrows to advance from slide to slide.

Note: Ironically, while it is viewable in Chrome and Firefox with all the fun JS bling, it is best viewed in Safari. When choosing a medium to build my presentation in I wanted to use impress.js because it provides a solid fallback, hence jiving with my preaching… Unfortunately, browsers aren’t quite up to all the 3d graphic rendering they claim to be. Even the bleeding edge ones… Except for Safari. (Although Chrome seems to be best for video… especially YouTube.)

Disclaimer: I am in the process of going through my live sites to implement the concepts I spoke about in my talk. I am not walking the walk 100% yet…

I will be posting notes for the slides over the weekend, and over the next few weeks I’ll be expanding on the ideas I shared in full blogposts. If you don’t want to miss any I’ll be tweeting them as they come out.

Please comment, share your ideas. If you think I’m talking $#!T call me out on it.


Announcing: The Redesign – Part One

Edit: So, since this went up I got a full-time job… My plans are now to clean up the blog design and focus on side project that will benefit the community. At some point I may return to the long-sideways scroll page… But for now it won’t be my focus.


I’ve been working on a new look for this site for a while… It’s not done yet, but I’ve gotten enough of the pieces in place to launch this iteration. As my wise friend Zach advised: “Commit early, commit often.”

You can play with the final concept, which is still under development, if you’re curious.

Technologies/Techniques Used

Home – (a.k.a. “Meet Jack”) Responsive. Play with the screen-size to check it out. I found that media queries worked well here.

About – (a.k.a. “What You Can Expect”) I developed a jQuery plugin – “Pretty Titles” – then ported that plugin into a WordPress plugin. There are a few kinks that need to be worked before I release the plugins into the wild. Stay tuned.

How does it work? Essentially it takes the content from an element’s title attribute and presents that content in an absolute positioned element, near the mouse position, that can be custom styled. The script will also keep an eye out for markdown formatted URLs. I am considering incorporating a limited markdown in the final version, the question is really how to avoid loading down the browser.

Portfolio – (a.k.a. “Recent Notable Projects”) I had started building a responsive jQuery slider but once Smashing Magazine announced FlexSlider I didn’t really see the need to create another one. Mine was going to be smaller and with fewer features. But I was only half done… So I implemented FlexSlider with a few minor design and functionality modifications.

I ported the jQuery plugin into WordPress as a plugin. The plugin functionality is accessed via a shortcode and you can choose a category, a tag or children of a page to be used for the content for the slideshow. I also integrated the plugin with ColorBox so that I could display information about the slide easily. In order for this to run smoothly I added an option to the original plugin so that the slideshow would pause when a colorbox overlay was open.

I am as yet undecided whether I will release this as a WordPress plugin.

Testimonials – (a.k.a. “What Others Are Saying”) This is my plugin “Random Excerpts Fader“, which I built live at WordCamp Jerusalem. I modified the plugin to work as a shortcode. The updates are live and can be downloaded from the WordPress plugin repository.

Blog – (a.k.a. “The Conversation”) This was the first stage of the redesign. I stuck to a simple layout and made it fully responsive.

Contact – Simple form. The QR code was created via vCard2QR, which I created to play with the QR concept.

What’s Still Missing

As I mentioned above, this is only a partial version of the final concept.

I ran into several challenges keeping the page responsive while maintaining the long horizontal flow. Media queries are adequate when the flexible elements do not need to have a fixed vertical size. If the elements can grow the queries are only needed to make sure everything looks good. But if you have fixed elements, as I am implementing here, just keeping the fonts fitting inside the parent element is a challenge. It’s a work in progress, but no need to delay the whole project when there is a working minimum viable project.

And of course…. Optimize, optimize optimize.