Debugging your code in WordPress: Tools of the Trade

As this is going live I am currently giving a talk at @WPNYC the WordPress New York Meetup group.

There are two slides I skimmed over due to lack of time, but they are  an essential part of the talk. In order to fulfill my promise to provide the complete story I am publishing this post with the full story.

Warning, this blogpost is a bit of a braindump. It is intended as notes to use to explore further. If you need something clarified, don’t heistate to comment.

The first slide is titled:

Tools of the Trade

With the following content:

  • Separate development environment
  • console.log() / error_log() / var_dump($var); die();
  • debug_backtrace() / Xdebug
  • Inspect Element / Developer Tools
  • A good IDE
  • Simulators
  • Unit Testing

Let’s dig in…

Separate Development Environment

Never go commando, period. There are always exceptions to the rule — when you cannot reproduce a bug on your development server while it’s glaring at you from production — but you should avoid coding live on production at all costs. Sooner or later you’ll break something and your site will be down, and it was perfectly preventable.

This is as important as not ever modifying core WordPress files.

There are many ways you can implement a development server. Keep in mind that the closer your development environment is to production in how it functions, the fewer bugs you’ll have due to discrepancies in implementation of your code.

  • XAMPP, MAMP and WAMP are all easy to use out of the box server solutions. I started out with them myself.
  • Vagrant is a great way you can channel your inner sysadmin. But you don’t need to be one to use Vagrant. The good people at 10up support VVV. Or you can use the vagrant box one I built and use.
  • Get another account on the server you are hosting your live site on. It’ll be worth the money, just make sure it’s not accesssible from the “outside.” Member’s only plugins can help with that. Or use the htaccess or nginx.conf files to limit access by ip address.

console.log() / error_log() / <pre>var_dump($var); die();

THE key to effective debugging is to know what you’re dealing with. These tools help you peek under the hood, test your assumptions, and understand what’s happening.

  • Console is a VERY effective tool; its most used method is .log but it has a lot more. It’ll help you see what’s going on in your JavaScript code. We’ve come far from using alert().
  • error_log is similar to console, but server-side. Find out where your error logs are written to on your host. A server isn’t worth it’s salt if it doesn’t provide that. If you enjoy console.log check out console_log().
  • While the error_log is cleaner, it limits its output. I find I like to see things in the browser, sometimes. I use this pattern, a lot, when debugging. echo '<pre>'; var_dump($var); die();
    It will “dump” the variable in a preformatted html tag, then die().

debug_backtrace() / Xdebug

Xdebug provides a whole suite of extended debugging methods. You don’t need to start here, but if you’re looking to up your game, here’s where to go.

Inspect Element / Developer Tools

Volumes of ink has been used talking about devtools, so I won’t go in depth here. devtools-window.png

Firebug changed our lives. Read up on it, use it. Personally, I enjoy designing in it too. It’s not just for debugging.

I used devtoops to build this mockup to nag @Dropbox to request a feature.

A good IDE

I use PHPStorm. A lot of people swear by Sublime. One thing I like about PHPStorm is that it has deep integration with WordPress.

The reason why this is essential is that it does a lot in the background to ensure good code.

  • It can autoformat, which means you’ll reduce your syntactical bugs.
  • Deep link to method sources, so you can more easily see what’s happening under the hood.
  • Code completion will help you make sure you’re using the right method, and give you a reason to should “DAMN YOU AUTOCORRECT” every so often.

Simulators

If you’re expected to support a specific device, you better test in it. Unfortunatly we can’t all afford every device under the sun, but there are a lot of tools out there to help us with that.

  • Modern.ie provides virtual machines for testing different versions of Internet Exploreer.
  • Use a mobile emulator sometimes making your screen narrower won’t cut it.

Unit Testing

This is the single most important thing you can do to prevent bugs. It’s hard to get started. It’s overwhelming. But as the proverb says: the best time to plant a tree is 20 years ago, the second best time is now.

Protip: Think about testing BEFORE you write your code… Look up TDD.


The second slide is titled:

WordPress Specific Debugging Tools

With the following content:

  • define(‘WP_DEBUG’, true);
  • Debug Bar plugin
  • All the Debug bar addons!!!
  • Style Guides

define(‘WP_DEBUG’, true);

There are a number of constants you can define in your wp-config.php file that can help your debugging in WordPress.

Debug Bar plugin

The Debug Bar is the equivalent to the devtools, but for WordPress. If you enable it you’ll get a window into how WordPress runs that you can’t get easily otherwise.

All the Debug Bar addons!!!

Expanding on the previous tool. There are a ton of plugins that hook into the Debug Bar and extend it.

Style Guides

This isn’t necessarily a WordPress specific tip, but if you’re using PHPStorm it comes with an auto formatting preset of WordPress’ code style.

In any case, it doesn’t matter how you style your code (tabs vs. spaces) but only that you are consistent. If you are consistent with your coding style you’ll prevent a whole lot of bugs. You’ll prevent a whole lot more if you’re working with other people and you make sure you’re all styling your code the same way.

Our brains evolved to see patterns, if your code styling isn’t consistent, you’ll miss details. You’ll have bugs.

Conclusion

I hope this was helpful. There’s a lot I didn’t cover so as to not overwhelm. What’s really most important, which I covered in my talk is the following:

Make it work, then make it work well.

If you do this, your code will always be improving.

How to see if a class was added to an element using JavaScript

If you need to see if a class has been added to an element the easiest way is to trigger a new event when you add the class.

$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged');

The problem with this solution is what happens if you do not have control over the function where this happens. Like if it happens in the WordPress core, and you know that you should never ever change code in the core.

I needed this for a plugin I was buidling. I know that when I click on something an ajax call is fired, and I want to do something when the response comes back. The ajax call is encapsulated so I can’t hook into it, but when the response comes back it adds a class to an element.

This is what I did:

checkForAddedClass = function (observedElement, className, callback) {
    var count = 0;
    const observer = setInterval(function () {
        count++;
        if (500 < count || $(observedElement).hasClass(className)) {
            clearInterval(observer);
            callback();
        }
    }, 10);
};

When I click on that something, I call this function. It sets an interval that watches the observedElement selector to see if the className was added. If it gets added, or 5 seconds goes by, it runs the callback.

This is how it would be implemented:

checkForAddedClass('.attachment-details', 'save-ready', getUpdatedSettings);

Hope this helps if you’re dealing with a similar issue.

The Launch: A React+Redux WordPress theme

I think it’s just about done, so I decided to go ‘live’ with it.

You’re looking at it now. What do you think?

Here’s my first post about this theme…

I’ll probably tweak it over the next weeks, months. But I’m itching to give it a test drive. For now it’s good enough for government work… which means a lot less than it did just a few months ago.

I’lll also write more about the process, and how it works asap.

Find a bug? Let me know.

 

Refactoring a WordPress plugin, Object-oriented, a start

I recently dissected  an Object Oriented WordPress plugin boilerplate. This exploration was part of a project I am undertaking to explore best practices for implementing Object Oriented principles in WordPress development.

When it comes to implementing coding principles, I’m generally not a purist — I aim to be utilitarian. One of the dictums I drum into my team is: “Make it work, then make it work well.” Do not take that to mean I’m sloppy, the second half of that statement holds as much weight as the first.

In the spirit of “make it work well”, I decided to refactor my Assets Manager plugin for this exploration, as I have not updated it in a while.

My goal here was not to create a pure Object Oriented plugin implementing all the glorious principles. There is a lot more I can do, and I will discuss some of those ideas as I explain what I did. Mainly, in this refactor, I wanted to accomplish the following:

  1. Implement the Single Responsibility Principle.
  2. Decouple the various components of the plugin from each other.
  3. Lay the groundwork for further implementation of more principles.

Single Responsibility Principle

Of of the banes of every developer is cutting through spaghetti code. I’ve discovered — from refactoring multitudes of lines of code — that the simplest, most effective way to reduce and prevent spaghetti is by applying this principle. Like spaghetti, your code cannot get tangled if it’s too short to tangle up.

Decouple the various components

While recompilation isn’t an issue with PHP/WordPress, there are still benefits to decoupling. First, reusability: if your components work independent of each other you can stash your pieces away for another project. You also don’t have to repeat your code if you need the same functionality elsewhere. Don’t Repeat Yourself!!!

But perhaps, more important than reusability is stability. The more interdependent components are in your project, the more fragile your project is overall. If you change one thing, the more other components depend on that piece, the more chance you have that you are breaking one of those other components.

This is the whole reason for the Open/Closed Principle as well as the Interface Segregation Principle. Aside from SOLID, though, this is also the reason why WordPress is riddled through and through with hooks. WordPress hooks allow for developers to change the functionality of the core, or other people’s plugins, without having to change the core, or foreign plugin, code.

Taking Stock

If you look at the previous version you’ll see that the extent of Object Oriented implementation is an encapsulation of the code, and that’s about it.

This isn’t a bad practice per-se. If you are going to keep to best practices of compatibility standards with WordPress, you cannot use php namespaces in your plugins. Namespaces were introduced in PHP 5.3 and, as of writing this, WordPress still supports as far back as PHP 5.2.4.

A first step you can take when implementing Objects in your WordPress plugins is to wrap your code in a class. If you do this, you do not have to worry about the names of your functions conflicting with the names of other functions in other plugins. This approach is called the “God Class,” as it creates one class that does it all. It’s not all that sophisticated, nor is it really Object Oriented either.

On this topic, once you start adding classes to your plugins, there is a fascinating and thorough breakdown of the different ways to instantiate a WordPress plugin as a class on the WordPress Stack Exchange community.

Following is a breakdown of the files in the new-and-improved plugin:

wp-asssets-manger.php

This should be renamed to match the directory (assets-manager), but I’m not sure whether the plugin upgrade process will work if I do this. Because this file is not named as the plugin directory, it makes generating test suites more complicated, but it’s also not a big deal.

The main job of this class is to instantiate all the other pieces of the plugin; I may implement an autoloader here at some point. While this class is dependent on ALL the other classes, since the only thing it does is instantiate all the other classes, it still is a fairly stable class. It doesn’t care about the intricacies of the other classes it uses. As long as the function names stay the same, you will only have to change this class if you need to add another component.

The other minor job of this class is to ensure that the rewrite rules are flushed when the post type is being created. Yes, this class is supposed to do one thing, but other, more pure ways of doing this would be convoluted — creating then deleting options in the database. I thought that that was silly to do simply to keep with a guideline, so I opted for this small infraction.

inc/Asset_Post_Type.php

When classes do one thing, they tend to be boring, and that’s a good thing.

I have an empty constructor here because the logical alternative would be to put into it  the hooks call. That would make tests more complicated, so I didn’t do that.

inc/Asset.php

I tried to include in here all the specific logic about how each individual asset works: the metadata, when are users allowed to access an asset, the asset link, etc. I did this to pull it away from the god class. The next step will be to pull out the specific restrictions as components onto themselves.

Currently, they all hook into pre_asset_serve which is a hook I put into the class that serves the asset. Each restriction should independently hook into the asset class.

Additionally, the UI is still intertwined with Admin.php, so if you were to add features to the asset, you would need to change that, as well as the JS file. I think this is a step in the right direction, perhaps next iteration will include this decoupling.

inc/Serve_Attachment.php

This does exactly what it says, nothing else. It hooks into WordPress before headers are sent, if the request is an Asset, it serves that request.

This was built with the Open closed principle in mind, open for extension, closed for modification. One of the most powerful features of WordPress are the hooks; which, are the embodiment of the Open closed principle.

Every WordPress developer learns at one point or another early in their career that you do not change the core, or anything that may be updated for that matter.

How is this learned?

Well, they make a change, to the core, or a plugin, or theme. Then, at some point in the future they forget that they had made that change and they update whatever it is they made the change to.

And everything breaks.

Well, maybe not everything; but whatever they were trying to accomplish with their modification is now lost.

Hooks are peppered throughout the core, well developed themes, and plugins. They allow other developers to hook into the code and tell it to do something without changing the code. This way when an update comes out, they can update without losing those changes.

Serve_Attachment.php has the hook do_action( 'pre_asset_serve', $this->attachment_id ); before the asset is served. I eat my own dog food here and hook into that action from Check_Asset_Restrictions.php to see if that asset should actually be served.

inc/Check_Asset_Restrictions.php

This is the other side of my implementation of the Open Closed principle, discussed in the previous file.

This class hooks into pre_asset_serve and runs all the checks it needs to. This class needs to have a certain amount of knowledge about how Asset.php works, so it’s not ideal. This is another example of how it’s a work in progress.

The fun thing about this is it runs entirely on hooks. It hooks into pre_asset_serve and it has a filter itself through which others can change the no_serve_message.

inc/Admin.php

This class is responsible for the admin display of the assets on the post type page.

As I wrote above. Ideally, each feature of the asset — expires, require login etc. –should be a separate component hooking in here, and where the file is served. Perhaps I’ll do that in the next iteration. Doing that would coincide better with the Interface segregation principle.

As-is, it think this approach is better than it was before. The admin display

inc/Update_Assets.php

This is the biggest violation of the Single Responsibility principle. On the one hand it’s responsible for the AJAX requests. On the other hand it’s responsible for ALL the AJAX requests. It wouldn’t be difficult to break up. Next version.

inc/Log_Assets_Access.php

Completely self-contained, hooks directly into pre_serve_asset, does (almost) one thing.

I put create_log_table() into here, because it is a single function that is needed to make it work. It’s static so it can be accessed on plugin activation without instantiating the whole class.

js/asset-manager.js

This could benefit from the implementation of a JavaScript framework. I’m considering BackboneJS for the next iteration of the plugin. I’d use that library since it’s already included in the WordPress core.

My goal for this file was twofold:

  • To implement wp.media.
    Back when I first built this, wp.media didn’t exist. I implemented  Plupload as a jQuery plugin in my original version. By using wp.media here I’m making the plugin “future proof.” If ever WordPress moves away from Plupload, they would implement whatever alternative via wp.media.
  • To break apart big functions.
    There was a huge spaghetti mess here before. Now that each “thing” is its own function I can iterate further in the next version.

Conclusion

This isn’t a finished product, nor is it the best I can do. But it’s a good step in the right direction. I learned a lot exploring what other people are doing with their plugins, and it was fun to flex my refactoring muscles to do this project. I hope you enjoyed, I did!

If you have any ideas about what steps you would want to see taken next, feel free to comment below, or use the contact form on the contact page.

Image credit

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:

[prettify] [/prettify]

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

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.

Conclusion

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:
[prettify]sudo apt-get update[/prettify]

Now we install the lamp server, run:
[prettify]sudo apt-get install lamp-server^[/prettify]

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:
[prettify]sudo touch /var/www/html/info.php[/prettify] [prettify]sudo nano /var/www/html/info.php[/prettify]

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:

[prettify]sudo /usr/bin/mysql_secure_installation[/prettify]

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:
[prettify]mysql -u root -p[/prettify] Enter the password you set for root.

Then create the database:
[prettify]create database wordpress;[/prettify] 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:
[prettify]sudo chown -R www-data:www-data /var/www/.[/prettify]

Then we need to add ourselves to apache’s group:
[prettify]sudo usermod -a -G www-data YOURUSERNAME[/prettify]

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.

[prettify]sudo chmod -R 775 /var/www/.[/prettify]

And Viola! WordPress time!

Download: http://wordpress.org/latest.zip

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.

“Submit”

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:
[prettify]sudo chown -R www-data:www-data /var/www/.[/prettify]

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

The code.

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

page-ajax_input.php

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.

inputtitle_submit_inc.php

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();

inputtitle_submit.js

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.

Summary

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.

Oops.

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