Using WordPress Shortcodes to Simplify your Editing
Development

Using WordPress Shortcodes to Simplify your Editing

Learn how to automate HTML generation and keep things simple

Update: There is a second part to this guide, Customizing the TinyMCE Editor to Add Buttons in WordPress, so you can take this functionality further!

Out of the box, WordPress offers a pretty decent spread of editor buttons to make your posts look good and read well, thanks to its use of the TinyMCE editor. However, if your blog has multiple contributors, each with varying degrees of HTML knowledge, you’re going to need to get creative to avoid those contributors creating a mess.

This is where learning how to build shortcodes in WordPress comes in. Building a shortcode or two will allow contributors to add more complex pieces of content to your blog without the headache of formatting or–gasp!–coding.

In my role at Axosoft, I’ve needed to create some buttons that help contributors insert various repeated content types. A good example is the blockquote. Citing an author and a URL can make this a potentially messy process when different people are writing. The TinyMCE editor can be a little quirky in the wrong hands, and we want things looking consistent across our posts.

So, I’m going to show you how to create a shortcode that removes the heavy lifting of coding a blockquote with a citation and automates it for the author. Rather than using the blockquote button that comes with the TinyMCE editor by default, authors will be able to use the simple blockquote we create, to add an author, citation, and link (all optional) and be done. It will end up looking like this:

Donec rutrum congue leo eget malesuada. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Vivamus suscipit tortor eget felis porttitor volutpat.
John Sparrow, Axosoft Blog

For simplicity, I’m going to do all the work in our theme’s functions.php file. I would recommend getting granular with function files so you can keep organized. (In the Axosoft theme, we have a functions folder, with a shortcodes.php file, and we require it from our main functions file.)

WordPress’s shortcode API has the info you need for reference. We’re keeping the shortcode functionality itself pretty simple; a shortcode with attributes, but none of those attributes have defaults.

Okay, let’s learn how to create that shortcode in our WordPress theme!

We need to create two things:

  1. A function that handles our shortcode.
  2. A call to add_shortcode, which registers that shortcode and ties it to the function, so it’ll be parsed.

Let’s start with the basics of the function:

function do_blockquote_shortcode( $atts = null, $content = null ) {

}

By default, we have no attributes and no content defined. However, when the shortcode is parsed, it will at least have content passing into the function.

Next, we’ll register this function by calling add_shortcode:

add_shortcode( 'blockquote', 'do_blockquote_shortcode' );

The function has two parameters. The first defines the shortcode in the square brackets. In our case, we are going to make shortcode simply called blockquote. The second parameter is the function we’re tying to that shortcode.

Inside the function, we’ll set up our content as the variable $output, and then return it at the end. We’ll start with opening and closing figure tags:

function do_blockquote_shortcode( $atts = null, $content = null ) {
    $output = '<figure class="quote">';
    $output .= '</figure>';
    return $output;
}

Not too exciting, yet! All it’s doing is adding our containing tags for the blockquote. Let’s add the content:

$output .= '<blockquote>' . $content . '</blockquote>';

Now, our function looks like this:

function do_blockquote_shortcode( $atts = null, $content = null ) {
    $output = '<figure class="quote">';
    $output .= '<blockquote>' . $content . '</blockquote>';
    $output .= '</figure>';
    return $output;
}

At the most basic level, this will work. It’ll insert the tags and place the content inside the blockquote tags. However, this is not much different from using the built-in button in WordPress. Let’s add some attributes that give authors a bit more power with their quotes.

We’re going to have 3 optional attributes:

  1. author: the person to whom the quote is attributed.
  2. cite: the name of the source; for example, The Verge.
  3. link: the URL of that source.

Here’s where we need to do some planning. We want to allow our authors to add an author, OR a citation, OR both. We can safely assume that if both of these attributes are missing, we do not need to append our figure tag with any source information. So, let’s create a wrapper that takes that into account:

if( $atts['author'] || $atts['cite'] ) {
    $output .= '<figcaption>';
    $output .= '</figcaption>';
}

Placed in our function, things look like this:

function do_blockquote_shortcode( $atts = null, $content = null ) {
    $output = '<figure class="quote">';
    $output .= '<blockquote>' . $content . '</blockquote>';
    if( $atts['author'] || $atts['cite'] ) {
        $output .= '<figcaption>';
        $output .= '</figcaption>';
    }
    $output .= '</figure>';
    return $output;
}

Now we can run through our attributes and output them if we need to. We’ll need to consider if any are dependent on one another.

The next chunks of code are going between our figcaption wrapper. We’ll bring it all into the function as a whole at the end.

Let’s start with whether or not an author has been defined:

if( $atts['author'] ) {
    $output .= $atts['author'];
}

Simple, right? But hold on, we need to plan ahead. We might have a link but no cite defined, in which case we want to wrap the link around the author. Let’s allow for that scenario:

if( $atts['author'] ) {
    if( $atts['link'] && !$atts['cite'] ) {
        $output .= '<a href="' . esc_url( $atts['link'] ) . '" target="_blank">';
    }
    $output .= $atts['author'];
    if( $atts['link'] && !$atts['cite'] ) {
        $output .= '</a>';
    }
}

Nice. Next, let’s add a comma if there’s a citation, to separate the author and citation:

if( $atts['author'] && $atts['cite'] ) {
    $output .= ', ';
}

Next, we can work on our citation. Since we only wrapped the author in a link if there was no cite attribute defined, it’s less complicated working with the citation and links. It’s all pretty straightforward.

if( $atts['cite'] ) {
    $output .= '<cite>';
    if( $atts['link'] ) {
        $output .= '<a href="' . esc_url( $atts['link'] ) . '" target="_blank">';
    }
    $output .= $atts['cite'];
    if( $atts['link'] ) {
        $output .= '</a>';
    }
    $output .= '</cite>';
}

If there’s a citation, we open the <cite> tag, check for a link, and open the <a> tag if one exists. We add the citation wording, close the link, and close out our <cite> tag.

Bringing it all together in our function, we have the following:

function do_blockquote_shortcode( $atts = null, $content = null ) {
    $output = '<figure class="quote">';
    $output .= '<blockquote>' . $content . '</blockquote>';
    if( $atts['author'] || $atts['cite'] ) {
        $output .= '<figcaption>';
        if( $atts['author'] ) {
            if( $atts['link'] && !$atts['cite'] ) {
                $output .= '<a href="' . esc_url( $atts['link'] ) . '" target="_blank">';
            }
            $output .= $atts['author'];
            if( $atts['link'] && !$atts['cite'] ) {
                $output .= '</a>';
            }
        }
        if( $atts['author'] && $atts['cite'] ) {
            $output .= ', ';
        }
        if( $atts['cite'] ) {
            $output .= '<cite>';
            if( $atts['link'] ) {
                $output .= '<a href="' . esc_url( $atts['link'] ) . '" target="_blank">';
            }
            $output .= $atts['cite'];
            if( $atts['link'] ) {
                $output .= '</a>';
            }
            $output .= '</cite>';
        }
        $output .= '</figcaption>';
    }
    $output .= '</figure>';
    return $output;
}

Here’s how we call it in the editor:

The blockquote shortcode in the editor

The blockquote shortcode in the editor

And here’s how it looks (of course, you can style your output however you’d like):

Donec rutrum congue leo eget malesuada. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Vivamus suscipit tortor eget felis porttitor volutpat.
John Sparrow, Axosoft Blog

That’s it! You’ve learned how to register a new shortcode in WordPress and allow for attributes to be defined within it. This should make your various contributors only have to use a simple piece of shortcode to output code that would otherwise potentially get messy.

I’ll be following up on this post with a second post, where we will create a custom TinyMCE button that will offer a UI for the attributes and then generate this shortcode automatically!

If your WordPress blog has multiple contributors, each with varying degrees of HTML knowledge, you’re going to need to get creative to avoid those contributors creating a mess when doing performing some complicated tasks. This is where learning how to build shortcodes in WordPress comes in. Building a shortcode or two will allow contributors to add more complex pieces of content to your blog without the headache of formatting or–gasp!–coding.

Stay on the cutting edge of software development by getting innovative tips, trends and stories delivered to your inbox every month!

Agile project management software
Plan, develop, review, and ship fast

Visit Axosoft.com

The downright luxurious Git client
For Windows, Mac & Linux

Visit GitKraken.com