Handy WordPress shortcodes

A bunch of ready to use functions created with the WordPress Shortcode API to enhance your administration experience.

By Luke Whitehouse on

PHPWordPress

Snippet

One of the great things about WordPress is it's ease in which it makes rather complex pieces of kit into user-friendly features that even the non-techies can understand. The WordPress Shortcode API is a prime example of this.

Over the years I've created many shortcodes that have been instrumental in saving users time and priming them with functionality that would otherwise be out of their reach. Here's a quick list of the more useful ones for you to plug into your projects. Let me know what you think and if you have any suggestions yourself then please leave a comment.

Table of contents:

Note: All my PHP functions in WordPress are prefixed with asrt, read why here.

Button

Sometimes you need the flexibility to change and add Call to Actions (CTAs) on your website, especially in content pages. As new content is added it may make sense to reposition the CTA or remove it altogether, so by introducing a shortcode which creates a new button with a few different options we can remove a web developer's input altogether.

Examples

As CTAs vary in importance I generally work with a few core variations and extend upon that where necessary. By default you can edit:

  • The 'theme', allowing for different styles of buttons, which could correlate to your website's colour palette;
  • and the size of the button, creating the button with a larger font-size.

Previewing the default options for the button shortcode

Fig 1: Previewing the default options for the button shortcode.

Usage

The shortcode can be installed by adding the following script to your functions.php file in your WordPress theme.

function asrt_btn_shortcode( $atts, $content = null ) {
  // Declare variables for later use
  $classes = 'btn';
  $class_attr = '';
  $link_attr = '';

  // Get shortcode attributes
  extract( shortcode_atts( array(
    'link'  => '',
    'theme' => '',
    'size'  => ''
  ), $atts ) );

  // Add new classes depending on shortcode attributes
  $classes .= !empty($theme) ? ' btn--' . $theme : '';
  $classes .= !empty($size) ? ' btn--large' : '';

  // Create string to output
  $output_string  = '<p><a href="' . $link . '" class="'. $classes . '">';
  $output_string .= $content;
  $output_string .= '</a></p>';

  // Return to $content hook
  return $output_string;
}

add_shortcode('button', 'asrt_btn_shortcode');

The CSS can be added into your theme's stylesheet, or using the wp_enqueue_style function.

.btn {
  display: inline-block;
  padding: .5em 1em;
  text-decoration: none;
  color: #222222;
  border: 0;
}

.btn--large {
  font-size: 1.2rem;
}

.btn--primary {
  background-color: #afdeb5;
}

.btn--secondary {
  background-color: #aed7ea;
}

You would then declare the button shortcode with the following syntax:

[button link="https://assortment.io" theme="primary" size="large"]Go to the Assortment website[/button]

Highlight panel

Another common requirement for a content managed website is to allow for highlighted panels within the content, either to promote a key sentence or to display some form of alert or warning.

Examples

Similarly to the button shortcode, the panel comes with a few default options to get you started:

  • The 'theme', allowing for different styles of panels;
  • and the 'size' of the panel's padding attribute.

Previewing the default options for the panel shortcode

Fig 2: Previewing the default options for the panel shortcode.

Usage

The shortcode can be installed by adding the following script to your functions.php file in your WordPress theme.

function asrt_panel_shortcode( $atts, $content = null ) {
  // Declare variables for later use
  $classes = 'panel';
  $class_attr = '';

  // Get shortcode attributes
  extract( shortcode_atts( array(
    'theme' => '',
    'size'  => ''
  ), $atts ) );

  // Add new classes depending on shortcode attributes
  $classes .= !empty($theme) ? ' panel--' . $theme : '';
  $classes .= !empty($size) ? ' panel--large' : '';

  // Create string to output
  $output_string  = '<p><div class="'. $classes . '">';
  $output_string .= $content;
  $output_string .= '</div></p>';

  // Return to $content hook
  return $output_string;
}

add_shortcode('panel', 'asrt_panel_shortcode');

Just as with the button shortcode, here's the default CSS which you can add into your theme's CSS files, or separately in Wordpress using the wp_enqueue_style function.

.panel {
  display: block;
  margin-bottom: .5em;
  padding: 1em;
  color: #222222;
  border: 0;
}

.panel--large {
  padding: 2em;
}

.panel--success {
  background-color: #afdeb5;
}

.panel--error {
  background-color: #efb5b5;
}

Once setup, you can access the panel shortcode with the following syntax.

[panel theme="success" size="large"]This is a success panel message box[/panel]

File

Extending on the functionality of the button shortcode is the [file]. Whilst similar in concept, the file shortcode is to be used when linking to a single file to be downloaded by your device (even if that file will be viewed in your browser).

The shortcode will examine the file and display it's file type and size to the user so they know this information before downloading the asset. This is especially useful if you're a user on a mobile with little to no data.

Examples

By default the button shortcode uses the primary theme that the button does, but also includes an extra class of .btn--icon should you require it. This ensures that your .btn CSS component is kept as modular as possible, only adding styles when required.

In addition, an HTML span element will be created after the text, giving you the option to add icons to the file element for the different types of files you work with. For example, if you had a video file, then you might use a video player icon.

Previewing the file shortcode

Fig 3: Previewing the file shortcode.

Note: The icon in this image has been taken as an example from Iconmonstr.

Usage

The shortcode can be installed by adding the following script to your functions.php file in your WordPress theme.

function asrt_file_shortcode( $atts, $content = null ) {
  // Declare variables for later use
  $output = '';

  // Get shortcode attributes
  extract( shortcode_atts( array(
    'link' => ''
  ), $atts ) );

  // Start construction of file button
  $output  = '<a href="' . $link . '" class="btn btn--primary btn--icon">';
  $output .= $content;

  // If $link is present
  if ($link) {
    // Get file info
    $file = get_headers($link, TRUE);

    // Get file size
    $file_size = $file['Content-Length'];
    $file_size = asrt_format_file_size($file_size);

    // Get file type
    $file_type_mime = $file['Content-Type'];
    $file_type_mime = explode('/', $file_type_mime);
    $file_type = end( $file_type_mime );

    // Output file info to file button
    $output .= ' (' . $file_size . ')';
    $output .= '<i class="icon icon--' . $file_type . '"></i>';
  }

  // Close construction of file button
  $output .= '</a>';

  // Return constructed file button
  return $output;
}

add_shortcode('file', 'asrt_file_shortcode');

In addition, you'll also require this helper function (taken from Stack Overflow) in order to convert the file's size from bytes into a more readable format.

function asrt_format_file_size($bytes, $precision = 2) {
  // Get all units of measurement
  $units = array('B', 'KB', 'MB', 'GB', 'TB');

  // Get and format value
  $bytes = max($bytes, 0);
  $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  $pow = min($pow, count($units) - 1);
  $bytes /= pow(1024, $pow);

  // Return based on precision scale
  return round($bytes, $precision) . ' ' . $units[$pow];
}

Afterwards, you can add a little CSS to the mix for your new .icon classes, dependant on the file types you're looking to support.

.icon {
  display: inline-block;
  vertical-align: middle;
  margin: 0 0 0 .25em;
  width: 20px;
  height: 20px;
  background-repeat: no-repeat;
  background-size: 100%;
}

.icon--jpg { background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTQuNTY4LjA3NWMyLjIwMiAxLjE3NCA1LjkzOCA0Ljg4MyA3LjQzMiA2Ljg4MS0xLjI4Ni0uOS00LjA0NC0xLjY1Ny02LjA5MS0xLjE3OS4yMjItMS40NjgtLjE4NS00LjUzNC0xLjM0MS01LjcwMnptNy40MzIgMTAuOTI1djEzaC0yMHYtMjRoOC40MDljNC44NTcgMCAzLjMzNSA4IDMuMzM1IDggMy4wMDktLjc0NSA4LjI1Ni0uNDE5IDguMjU2IDN6bS0xNSAxLjVjMCAuODI4LjY3MiAxLjUgMS41MDEgMS41LjgyNyAwIDEuNDk5LS42NzIgMS40OTktMS41cy0uNjcyLTEuNS0xLjQ5OS0xLjVjLS44MjkgMC0xLjUwMS42NzItMS41MDEgMS41em0xMCA2LjVsLTMuNS02LTIuMDkzIDIuOTY4LTEuMzEtLjk2OC0zLjA5NyA0aDEweiIvPjwvc3ZnPg=='); }
.icon--mp4 { background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTEuMzYyIDJjNC4xNTYgMCAyLjYzOCA2IDIuNjM4IDZzNi0xLjY1IDYgMi40NTd2MTEuNTQzaC0xNnYtMjBoNy4zNjJ6bS44MjctMmgtMTAuMTg5djI0aDIwdi0xNC4zODZjMC0yLjM5MS02LjY0OC05LjYxNC05LjgxMS05LjYxNHptLTMuMTg5IDE4di03LjAybDYgMy41MjctNiAzLjQ5M3oiLz48L3N2Zz4='); }

Once setup, you can access the file shortcode with the following syntax.

[file link="https://unsplash.it/400/400"]Download this image[/file]

Introductory paragraph

A common request from clients is to have the ability to provide an introductory paragraph within the WYSIWIG editor itself, rather than using the default excerpt field. If you take the example of a blog, you may feel it necessary to have a different description on the listing of a post rather than on the post's page itself.

To tackle this, you can create an intro shortcode which surrounds the text in a div tag with the class of intro...

function asrt_intro_shortcode ( $atts, $content = null) {
  $output = '<div class="intro">' . $content . '</div>';
  return $output;
}
add_shortcode( 'intro', 'asrt_intro_shortcode' );

... and then style that up as appropriate.

.intro {
  font-size: 1.2rem;
}

Site information

Another reoccurring scenario is the ability to dynamically access site information from a central location, such as your facebook URL or Company phone number.

Normally if you wanted to update any of these, you'd have to go through every occurrence and manually update them one by one. However, storing the values in a central location like a settings page and then creating shortcodes to get this information means your client has a centralised location to update all references, saving a whole lot of time.

Personally, I swear by the Advanced Custom Fields (ACF) plugin, so all the Site Information shortcodes will get information from the ACF Options page.

Social media

Here's ones for Facebook, Twitter and LinkedIn, getting the respective social media network's usernames.

// facebook
function asrt_shortcode_facebook( $atts, $content = null ) {
  $output_string = '<a href="https://facebook.com/'. get_field('facebook', 'options') .'">Facebook</a>';
  return $output_string;
}
add_shortcode( 'facebook', 'asrt_shortcode_facebook' );

// twitter
function asrt_shortcode_twitter( $atts, $content = null ) {
  $output_string = '<a href="https://twitter.com/'. get_field('twitter', 'options') .'">Twitter</a>';
  return $output_string;
}
add_shortcode( 'twitter', 'asrt_shortcode_twitter' );

// linked in
function asrt_linkedin_shortcode( $atts, $content = null ) {
  $output_string = '<a href="https://www.linkedin.com/in/'. get_field('linkedin', 'options') .'">Linked In</a>';
  return $output_string;
}
add_shortcode( 'linkedin', 'asrt_linkedin_shortcode' );

Generic company information

Similarly, you may wish to get access to geenric company information, such as the company phone number, email address, etc.

// Phone number
function asrt_phone_shortcode( $atts, $content = null ) {
  $phone = get_field('company_phone', 'options');
  $output_string = '<a href="tel:'. $phone .'">' . $phone . '</a>';
  
  return $output_string;
}
add_shortcode( 'email', 'asrt_phone_shortcode' );

// Email address
function asrt_email_shortcode( $atts, $content = null ) {
  $email = get_field('company_email', 'options');
  $output_string = '<a href="mailto:'. $email .'">' . $email . '</a>';
  
  return $output_string;
}
add_shortcode( 'email', 'asrt_email_shortcode' );

Page title

Sometimes it's useful to get the current page's title, rather than writing it out everytime in case you change it. i.e. a property page for a travel agents.

function asrt_title_shortcode( $atts, $content = null ) {
  global $post;
  $output_string = get_the_title($post->ID);
  return $output_string;
}
add_shortcode( 'title', 'asrt_title_shortcode' );

Responsive iFrames

Finally, it's common for a client to want to embed an iframe into the website, be that for a Youtube, Vimeo player or even something more interactive such as Google Maps. Whatever the case, we want the output to be responsive and scale dependant on the device you're using. To do this, we can create a shortcode to wrap our iframe in a flexible element using CSS.

All that the user is required to do is provide the embed URL for the iframe.

Copy and paste this shortcode into your functions.php.

function asrt_shortcode_embed( $atts, $content = null ) {
  extract( shortcode_atts( array(
    'link'   => ''
  ), $atts ) );

  $output_string = '<div class="flexible"><iframe src="'. $link .'" style="border:0;" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>';
  return $output_string;
}
add_shortcode('flexible', 'asrt_shortcode_embed');

And copy the CSS into your theme. You'll notice this uses the Viewport Width CSS unit, if you require support <IE9 then you may require some fixed heights with breakpoints or a padding trick.

.flexible {
  position: relative;
  height: 56.25vw;
  overflow: hidden;

  iframe,
  object,
  embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}

I hope this list of shortcodes sets you off on your path of discovery with the WordPress Shortcodes API, it's an incredibly powerful system and your users will love you for it, just make sure not to go overboard. Keep it simple, stupid.

Until next time 

Follow us on Twitter, Facebook or Github.
© Copyright 2021 Assortment.
Created and maintained by Luke Whitehouse.