Organize your WordPress Theme in 3 Easy Steps

Like many developers out there, I do my best to write clean and manageable code. Read on to find out three simple steps to make your WordPress themes better than ever.

I make an effort to keep my code clean for two reasons, ease of use and maintainability. It’s far easier to fix bugs or make updates to the code if it’s clean. It will take much more time if six months or a year from now you need to re-examine your code to figure it out, rather than just fixing the issue. I also am a firm believer in the saying “if you’re going to do it, do it right the first time.” and by proxy “make it right”. Every developer sees some “bad code” at some point, sometimes they may have even written it. I feel it’s important to correct wrongs as you see them and improve your own code as you go.

That’s no easy task, but WordPress makes it a little easier when it comes to theme development. Here’s three steps you can take to make your themes a little better than before.

Step One: Proper Template Directories

This is more of a general step you can take, but still useful, and it’s as simple as creating folders to organize your files in. Many developers like to have seperate folders for JavaScript, CSS, and images. These are the folders that I use to keep everything in its place:

  • /theme-directory/css/
  • /theme-directory/images/
  • /theme-directory/js/
  • /theme-directory/includes/

That last one is important. Anything custom that i’m building for the theme, such as a meta box or option page for the admin section of WordPress, would live in this folder. I used to put some front end PHP in there as well, but more on that later.

Step 2: Registering your CSS and JavaScript

WordPress comes with several functions you can use to queue and load your CSS and JavaScript files. You can set a version number for the files, and even tell WordPress that a specific file requires a previously queued file before this one loads (for example, requiring that jQuery is loaded before a jQuery plugin your theme needs gets loaded).

Step 3: Use WordPress Template Files!

WordPress is built around themes and plugins, and it’s really easy to make your theme easy to manage if you use what has been given to you. The best example of this is the function get_template_part(). This function allows for you to split your template files into smaller more manageable blocks of code. For example, you can make a loop.php file that you can use in all of your template files and include it simply by calling get_template_part(“loop”). It’s just that easy! You can use this function to display any file you make in the main template directory, the possibilities are endless.

That’s all there is to it. Check out the following links for more information.


Awesome WordPress Feature of the Day: Add Theme Support

This has become one of my favorite features when I build a new WordPress theme. It seems like such a simple thing, but when I started coding my themes with this function in mind everything melds together so nicely.

My favorite new function in WordPress is Add Theme Support.

As a developer, one of my favorite things to do is write reusable code. I love when I start a theme and find it needs some bit of functionality that I wrote for something else, if all i need to do is include a file and make a couple strategic edit my job just got easier. Here is a quick example. Imagine you have a custom post type for events ( just an example, I have no code to back this up, sucks I know). If you create your event post type in a class, you can use the current_theme_supports method to check and see if you need it, and your class does the rest!

add_action("init", "jmh_event_post_init");
function jmh_event_post_init() {
global $event_class;
$event_class = new event_post_class();

So if you build a lot of themes, set up a single folder with an init file. include all your files there, organize it, then your functions PHP will just need to start off with a couple things:

require_once('your init php file');

First Impressions: Genesis Theme Framework

Lately I’ve been doing a lot more work with WordPress, and it’s given me the opportunity to work on lots of different themes and theme frameworks. Given the choice I would much rather start a new theme from scratch. Of course “from scratch” means using one of the many starter themes people have put together, recently my favorite being BLANK from the Digging into WordPress Theme Clubhouse. However when working in a production environment I’ve found it beneficial to find a framework and stick with it. That way projects get done faster, everyone uses the same codebase, and clients all get a similar experience.

Enter the Genesis Framework from StudioPress. As soon as I got a look at how the framework is built I was instantly impressed. First, it has several great features that are helpful to both developers and users. It offers automatic updates, great security, customizable theme settings, custom widgets, plenty of layout options, and the list goes on. There are a lot of frameworks out there that give you similar things, but Genesis has some really cool features for developers too.

For starters, the theme is fully compatible with all the new features in WordPress 3.0. StudioPress was quick to add those features for their users, and that kind of dedication to their product is a huge value. Another great value for developers is the themes construction. They have built Genesis to be a starting point for child themes, allowing for radically different sites without having to do the same edits to the main theme over and over again. To help make a child theme as customizable as it needs to be in order to be successful, they have built in plenty of hooks to do whatever you need. If you want to add a widgetized area above the footer, it’s easy. You need an add area above the content, it can be done. Anything you can think of you can do. Proof of this is easy enough to find, since from what I can tell every theme that StudioPress has available is a child theme of Genesis.

On top of all this, StudioPress has an active community of users and developers on their forums that can offer help to any problems people come up with. I think anyone who really uses WordPress knows how important an active community can be.

To wrap this up, I can simplify my first impressions into one word : awesome. I’m really looking forward to building some cool stuff on top of this theme framework, and when I do i’ll be back writing a post about it.

JSON vs. XML: What Should You Use?

Lots of people have asked me this question: which is better when loading data via an ajax request? JSON is my favorite. I’m going to try and explain the benefits of JSON over XML.

From the start, JSON is already has a leg up on XML for one reason: it’s faster. To read XML you need to parse it, read the nodes, attributes, and child nodes in the XML document, and then use the data that you’ve found.

In jQuery the easiest way to do that is to use the built-in ajax functions to call the XML and use the each function to loop through all the nodes. The each function is nice, but is much much slower than a for loop. Just imagine what happens when we have an XML document with multiple levels of nested nodes you need to get at. You end up with multiple nested $.each functions and without much trying, you end up with a script that crawls. With JSON it’s easy to get at the data since its already native javascript. No parsers or proxies necessary–all you need to do is loop through the data, fast and simple. That’s one point for JSON.

There are aspects of XML that people point to as reasons to use it. First, XML is both human and machine readable. It is nice to see what data is being returned just by viewing the source, but that problem is solved by having good documentation, including an example of the JSON that will be returned. Also, being a front-end developer, I spend a lot of my time reading javascript anyway. I find it just as easy to read as XML, it’s just different.

Another good reason to use XML is that it’s widely available. Lots of websites offer APIs to get at their public (and sometimes private) data, and I usually find the returned format of these APIs are often either XML or JSON. However since XML has been around longer than JSON, there is simply more XML out there.

Sometimes you might find yourself in a situation where you don’t have JSON as an option. So do you submit to the API gods and slow down your site and just use the XML? Why do that when you can write the API yourself! This is where some server side skills come in handy. It’s super easy to load an XML document via PHP and print out the data in whatever format you need it to be in.

So in conclusion, you should be using JSON every chance you get.

jQuery's document.ready(), What is it and Why is it Useful?

The document.ready() function is the first thing anyone should learn about jQuery. This function will allow you to take all that ugly behavioral javascript out of your markup.

Lets face it, nobody likes all those javascript:void(0); in the anchors href. As for that body “onload” function call, can that too, its no good. All that ugly code in the markup is just plain bad news.

With jQuery and document.ready() you can put all your event driven javascript in one file, making it easy to maintain and upgrade later. The document.ready() function works just as the name implies. Document refers to the DOM, or Document Object Model, while in this case “ready” refers to when the DOM is registered by the browser.

Before we start, make sure you have jQuery included on your page. For a quick refresh on how that’s done, click here.

Using the document.ready() function is really easy. Check out this example:

		//insert code here
		alert("this will flre when the DOM is loaded.");

As with most code, there is a shorthand version of the document.ready() function. In jQuery, any function passed to the jQuery object will be bound to the document.ready() function, as seen below.

		//insert code here
		alert("this will work the same as the code above.");

This is how you would add a click event to all the anchor tags on your page using the document.ready() function.

			alert("you clicked me!");

That’s all there is to it. Are you having an issue with jQuery, or any code you need some help on? Have an idea for an article you’d like to see? Feel free to leave a comment with any questions or suggestions.

Adding Twitter to your site with jQuery Part 2

This series of articles will explain how to retrieve information from Twitter using their API, and ways you can display it on your website in an attractive way. In Part 2 we will add some simple CSS to the tweet to make it look nice, and display all the data the twitter API returns.

As a special bonus for all four of you who will read this post, i’ve also built this into a jQuery plugin. First we will start by changing what we did in the last post a bit by creating a unordered list to hold the tweets.

	var $tweetContainer = $(document.createElement("ul"))

We will use each list item to hold the tweet data. I added an if statement that will add a class to easily style even and odd tweets, and then we add the code to include the users Twitter avatar and the tweet text.

	var tweetClass = "odd";
	if(i%2 == 0){
		tweetClass = "even";

     var $tweet = $(document.createElement("li"))

     var $tweetPhoto = $(document.createElement("img"))

     var $tweetDesc = $(document.createElement("div"))
                  	 	.html(""+tweets[i].from_user+": " + base.replaceURLs(tweets[i].text));

You’ll notice there’s a function in there called replaceURLs:

	base.replaceURLs = function(text){
		text = text.replace(base.options.aTagRegexp,"$1");
		text = text.replace(base.options.userRegexp,"$1@$2");
		text = text.replace(base.options.hashtagRegexp,"$1#$2");
		return text;

This function will search through the text of the tweet and take urls and make them clickable, as well as finding twitter users and hash tags and linking those correctly as well.

Now we need to display when the tweet was created. That should be too bad right, we just create an element and use it to display the date. Normally when working with dates i’d say that was OK, except twitter is all about instant gratification. We want to know what’s happening and how long ago it was when it happened. Its for this reason we need a little extra code so we can display when a tweet was created in relation to the current time.

First we need to get some values to compare the tweets created date against:

	var minDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(60*1000));
	var hourDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(60*60*1000));
    	var dayDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(24*60*60*1000));

Then all we need to do is write our compare logic. The seconds and minutes are obvious choices, but choosing when to stop displaying a message like “2 days ago” vs displaying the tweet date is up to you. For the plugin I went with 5 days. We will also be providing a link to the app used to post the tweet, very helpful considering there are about 800,000 different apps out there.

	if(minDiff < 59){
		timeDiff = "
about "+minDiff+" minutes ago from "+base.fixEncHTML(tweets[i].source)+"
"; }else if(hourDiff < 24){ timeDiff = "
about "+hourDiff+" hours ago from "+base.fixEncHTML(tweets[i].source)+"
"; }else if(dayDiff < 5){ timeDiff = "
"+dayDiff+" days ago from "+base.fixEncHTML(tweets[i].source)+"
"; }else{ var AMPM = "PM"; var myHours; if(tweetDate.getHours() < 12){ AMPM = "AM"; if(tweetDate.getHours() == 0){ myHours = "12"; }else{ myHours = tweetDate.getHours(); } }else{ myHours = tweetDate.getHours()-12; } var myDate = tweetDate.getDate() +"th"; if(tweetDate.getDate() == 1 || tweetDate.getDate() == 21 || tweetDate.getDate() == 31){ myDate = tweetDate.getDate() +"st"; }else if(tweetDate.getDate() == 2 || tweetDate.getDate() == 22){ myDate = tweetDate.getDate() +"nd"; }else if(tweetDate.getDate() == 3 || tweetDate.getDate() == 23){ myDate = tweetDate.getDate() +"rd"; } timeDiff = "
"+myHours+":"+tweetDate.getMinutes()+" "+AMPM+" "+base.months[tweetDate.getMonth()]+" "+myDate+" from "+base.fixEncHTML(tweets[i].source)+"
"; }

Finally, we can add a couple useful links that will help users view and reply to the tweets:

	var $tweetLinks = $(document.createElement("div"))
                  	 	.html("Reply · View Tweet");


Thats all it takes to write out a tweet, al this code will get you something that looks like this (i know, the colors are awful):

tweets example.png

That was a bunch of code. I hope you enjoyed this series of posts, and I promise if I ever do a series of posts again i’ll write them all first before posting :-)

Check out this quick demo and of course, the plugin source code.

Adding Twitter to your site with jQuery Part 1

This series of articles will explain how to retrieve information from Twitter using their API, and ways you can display it on your website in an attractive way. Part one we will go over the basic of the Twitter API and look at some simple code that will print out a list of tweets.

For this example I will use my own tweets, feel free to follow me @jaredharbour.

What is Twitter?

In recent years, social media has become a huge part of peoples lives. Sites like MySpace, Facebook and LinkedIn (which I sometimes refer to as ‘The Big Three’) allow people from all over the world connect and share their lives and ideas instantly. Recently Twitter has become the next big addition to the global conversation. Twitter is unique among the others in that its only function is to accept and display 140 character “micro-blogs”. Let me get one thing out of the way before we continue, micro-blogging doesn’t mean every message has to be about taking out the trash and mowing the lawn. There are 5 million+ Twitter users in the world today, and that number will only get bigger. Now lets get into some code.

The Twitter API

The Twitter API attempts to conform to the principals of Representational State Transfer or REST. I’ll leave it to you to read up on what that means, simply put it means that with the Twitter API you simply need to change the extension to get your results in a different format.

Since we just want to print out a list of tweets, we will start by using the search function. The search function will return its results in two formats, XML and JSON. We will use JSON because in my experience it’s faster and easier to use than XML.

For a more in depth look at the search function take a look at the Twitter documentation. Now lets get to the jQuery part. We get to use one of my favorite methods jQuery gives us, jquery.getJSON. This handy function will return the JSON via a GET HTTP request, just what the doctor ordered.

    function(data) {
        // our code to handle the data here

That’s not all though, we need to get at our data. jQuery makes it easy with the each function. This will let us loop through the JSON object with ease. In this case, “tweets” becomes our array of data. Then we need to check a few things to make sure we are in the section of the object we want. This logic isn’t perfect, but it will work for all the major browsers. The first and second if statements are to check if there are tweets to look at. I needed them both because it seems IE was unhappy with accessing the first element, because in some cases there isn’t one. The third if statement makes sure that what we’re looking at is in fact a tweet, and not some random piece of data.

$.each(data, function(i, tweets){
	if (tweets.length != undefined){
		if (tweets[0] != undefined){
			if (tweets[0].created_at != undefined){


Now we just need to print out some data. Just a simple for loop and a document.write and we’re all set.

for(var i = 0; i < tweets.length; i++){
"); }

That’s all there is to it! In the next post I will get into formatting the tweets to add more functionality. Here are some of the topics I will cover later in the series.

  • Hyperlinking hash tags and users
  • Formatting tweet time and date
  • Linking to the Twitter app

Have a question? Looking for something specific? Leave a comment and I’ll get back to you!

We're attending the jQuery Conference!

That’s Right! We are signed up to join 298 other web professionals in Cambridge for this years jQuery Conference. The conference will be held September 12th and 13th at Microsoft New England Research and Development Center in Boston, MA.

We are really excited. We are waiting to see what topics are going to be covered, but we know there will be a 3 hour seminar for jQuery beginners that at least one of us will check out. We are also looking forward to meeting other people in the area who use jQuery, maybe exchange some ideas about jQuery or even the web in general.

If you want some information about this years jQuery conference, check out some of the links i’ve listed below. Also check back here for more updates, as we will be posting any new information when we get it. We will also be posting our live feedback while at the conference via Twitter. Follow @think2loud for all the updates.


Keep up with the details of the jQuery Conference here. Only a month to go!

Reading XML with jQuery

Welcome to my first of many articles for Think2Loud! Today I thought I’d start with something simple that will lead into several other topics. So here we go, head first into reading XML with jQuery.

The first step is making sure you have jQuery included on your page.

Second, you should check the XML file you are going to read and make sure it’s free of errors. If you are unfamiliar with XML synatax, check out the W3School’s rules on XML syntax. The file I’m using for this example is just a listing of some Web sites I enjoy.

Finally, you just need to tell jQuery to read the file and print out the contents. Start by adding the document.ready function to the page.



Continue reading “Reading XML with jQuery”