Wednesday, July 28, 2010

Wordpress Shortcodes

Haven't done much work with Wordpress before, but a few of our current contracts have required us to dig in pretty deeply. Wordpress is impressive in how it can hide the guts from the users and authors while letting us get at the back end to tweak and make updates.

One of the features we thought was missing was some way to do simple text replacement for pieces of text or html that repeat in a lot of places. We spent our time Googling for things like wordpress macro, wordpress text replace, auto-complete and others. We found lots of plug-ins but none were really what we wanted or were not certified to work with the versions of Wordpress our clients are using.

Then we stumbled across the proper vocabulary word: shortcode! Wordpress has a whole api and everything. Basically though, a shortcode is just a php function that returns some value when called. Another little function call to add_shortcode placed in the functions.php file is all that is required to set them up.

The best part is that for most Wordpress themes, the functions.php file can be edited from the administrator interface. So, we don't need access to our client's server or ftp. This will make maintenance much easier in the future.

Here is a simple example:
First we have the function we want
function TA_address(){
return '<a href = "http://www.tyreeapps.com">Visit our website for good times</a>';
}

Then just below that in the functions.php file we add our shortcode to Wordpress' master list

add_shortcode('TAwebsite','TA_address');


Now we can enter our new shortcode [TAwebsite] into our Wordpress pages wherever we want to have our website address. We can enter this from the regular blog post or page editor. We don't even have to switch over to the html view. And perhaps the best part of the whole deal...we can change the string that the shortcode returns in one place and it instantly changes across our whole website.

So, if there is a piece of code you need on EVERY page of your site, edit the template file. If there is a piece of code you need at the same place on every page, look at the widgets and menus. If there is a piece of code that you need a lot but not everywhere, then a shortcode might be just the ticket.

It is important to note that if your shortcode is named the same as another shortcode bad things will happen. Best practice is to prepend your shortcodes with some identifier (like "TA" for mine) that is unlikely to be used by other people. The more we use open source stuff, the more we're realizing the importance of getting to the habit of adding an identifier to ALL functions and other broadly scoped objects.
Shortcodes can do much more than just text replacement. Here is a nice list of some more advanced usages.

No comments:

Post a Comment