Understanding and Applying WordPress Shortcodes

by in WordPress on 5th Nov 2012 · Comments

One of the best features included with every installation of WordPress is also one of the most overlooked. Known as shortcodes, this feature actually allows developers to bundle entire pieces of XHTML or PHP code into a small variable that can be placed throughout the installation's posts, page content, and even its template files with a little trickery.

They're the perfect way for amateur WordPress users to start modifying the look and feel of their templates as well as their site's content, and they're a perfect option for more advanced users who can create their own customized shortcodes in just a few easy steps.

All About WordPress Shortcodes

All About WordPress Shortcodes

These small variables have a number of benefits for WordPress users of all types, and they're an important part of the process when developing engaging templates and robust content. With shortcodes, entire posts can be given new life through things like embedded video, advanced text formatting, or including plug-in code within a post where it otherwise would not be permitted.

Templates are Pretty Straightforward, So Why Use Shortcodes at All?

Perhaps the reason that WordPress shortcodes are so easily and frequently overlooked is that there's a little confusion about just what their utility is. When most people think about developing a theme or even a plug-in for WordPress, they commonly think of things like the WordPress Loop, PHP functions and filters, and other advanced routines that are essential to making things work.

But those things should be considered the "framing" of the WordPress installation. On top of that framework, small shortcodes provide added functionality and enhancements to the most major features of WordPress.

Additionally, shortcodes can bring a plug-in's output directly into the body of a custom page or into a post's content itself. These two areas are specifically prohibited from containing PHP code; shortcodes are the only way, aside from hacking core WordPress files, to add truly dynamic content to these more static areas of the installation.

While most plug-ins already come bundled with their own shortcodes so that their features can be embedded directly into a page or post, a number of other WordPress features don't ship with a shortcode for use throughout the Dashboard. In these cases, it's necessary to create a custom shortcode that can perform the desired function.

It might sound complicated, but creating a shortcode is actually a very easy process - even for the newest WordPress users out there.

Step 1: Locating the Proper File for Shortcode Definition
In order to create a shortcode, WordPress site administrators will need to log into their site's server via FTP and edit the functions.php file that is included with every theme. It's worth noting that there are two kinds of functions files within every WordPress installation: The first of these files is a site-wide file that is created by the WordPress developers themselves, and it's located in the wp-includes folder.

A file of the same name also resides in the root folder for each theme installed to the server. This is the one that will be modified, as it won't be changed during a software update and it doesn't stand a chance of ruining core WordPress features in the much larger, site-wide version of the file.

For reference, the functions.php file needed for this process is generally located in the following location on the server:

/home/public_html/wp-content/themes/YOUR-CURRENT-THEME/functions.php

Only the functions.php file associated with the currently activated theme should be modified. Changes to any other file won't show up on the live version of the website, and that might create some confusion.

Step 2: Defining the Shortcode in functions.php
With the theme-specific "functions.php" file open and ready to receive new code, it's time to define a new function. This function will be responsible for producing a much longer piece of code every time the smaller shortcode is placed into a page or post. The first segment of code should look like the example below, which will return a standard WordPress log-in box anywhere the shortcode is used:

function shortcode_login() { 

    return 'extract( shortcode_atts( array('redirect' => ''), $atts ) );

    if (!is_user_logged_in()) {
        if($redirect) {
            $redirect_url = $redirect;
        } else {
            $redirect_url = get_permalink();
        }
        $form = wp_login_form(array('echo' => false, 'redirect' => $redirect_url )); 
    } 
    return $form; 
}

Next, it's time to define the actual shortcode variable that will be placed between brackets in order to produce the code inserted above. That is actually the easiest part of this entire process, and it requires just one more line of code to be placed into the theme-specific "functions.php" file. The code necessary to do this looks like the following example:

add_shortcode('loginbox', 'post_ad');

The add_shortcode function requires only the name of the shortcode, followed by the name of the function that it will process and display. In this case, we've named our shortcode "loginbox". This will appear in pages and posts as [loginbox] when its functionality is desired. In this example, it is instructed to pull code from the post_ad PHP function created earlier in this step of the tutorial.

That function contains advanced code that pulls the log-in box directly out of the core WordPress files, making it easy to place and style the resulting output.

Though this shortcode is pretty advanced, it could be used to do virtually anything. A shortcode could just as easily be used to print some standard text, or place a pre-defined image into a post without using a bulky img tag every time that functionality is required. Simply alter the text after between the brackets in the first function, and then update the name of the shortcode in the add_shortcode statement afterward.

An unlimited number of shortcode definitions can live in the theme's functions.php file, but those shortcodes will need be transferred between themes as a website changes its design.

Step 3: Bug Test the New Shortcode(s)
After a new short code has been created, it's time to place it into a page or post and save the new content for viewing on the website. Then, navigate to the relevant part of the website and test the shortcode's functionally.

If the example above has been executed successfully within the "functions.php" file, placing the [loginbox] shortcode into a page or post will result in a standard WordPress login form being generated wherever the code is displayed.

If the code does not display, make sure that the correct shortcode variable has been defined in the functions file, and check for any typos in the page or post where the new shortcode appears.

What if a Shortcode is Best Used Outside of a Page or Post?

Every now and then, a situation arises where a shortcode needs to be used outside of a typical page or post. This is most often the case when a WordPress plug-in includes only a shortcode in order to implement its functionality, rather than including standard template variables or even a sidebar widget. Thankfully, the developers behind WordPress have recognized this significant need and they've developed their own PHP routine for exporting a shortcode into existing template files.

In order to export a shortcode and place it into an existing template file, it must be placed within a PHP variable. The shortcode itself essentially appears as an "argument" for the variable, defining its output.

If we were to take the [loginbox] shortcode created earlier, and export it for use in one of the template files our theme includes, it would look like this:

<?php echo do_shortcode('[loginbox]') ?>

The do_shortcode function and variable is pretty easy to use. If the shortcode contains its own elements, those can be included in the shortcode too. For example, our log-in box might have multiple styles, named blue, red, and green. To place a green log-in box into a template file, we'd produce an included shortcode like so:

<?php echo do_shortcode("[loginbox style='green']") ?>

Essentially, the variable's argument can be a completely normal, natural shortcode of any variety. The template will parse the shortcode as if it were native PHP, and the template will output it in the same way that the Dashboard would when the page is rendered.

More Resources

Shortcode = Shortcut

Shortcodes could also be considered shortcuts, as they help reduce the lines of code necessary to perform basic functions within pages and posts. When placed inside a PHP string, they can even be used to enhance templates and build upon WordPress's existing functionality. With a little testing, and a bit of skillful development within functions.php, this essential WordPress feature no longer needs to be overlooked.

Have you implemented WordPress shortcodes? Share your thoughts with us.

Terrance is a versatile web developer and the technical editor at OXP. He enjoys creating functional websites and is particularly engrossed in all the tiny details mixed together to construct great user experiences. He always believe that every web user deserves the best!