WordPress: Adding shortcodes to themes

Overview

WordPress and many of its plugins automatically add shortcodes to your theme which you can then use in your pages and posts. A shortcode looks something like [myshortcode].

In this blog post I will describe how to create your own (and show you how easy it is) as well as give examples for some more useful shortcodes that can make your web designing life a bit easier.

First thing you need to do is locate your functions.php file in your theme folder (If it exists – if it doesn’t, just create one from scratch). The standard location will be:

/your-site/wp-content/themes/your-theme/functions.php

Inside the functions.php file, add the following code to add a shortcode to your theme:

<?php add_shortcode( $tag , $func ); ?>

where $tag is the shortcode you will use in your posts and pages and $func is the function you want to call.

Examples

  • In this example, we are adding a shortcode we can use in our posts and pages that refers to the URL of our site.
    <?php add_shortcode('site','site_url'); ?>
    
  • So when adding an image to a page in WordPress for example, we can use the code:
    <img src="&#91;site&#93;/wp-content/uploads/someimage.jpg" />
    
  • This makes life easier if we are copying and pasting our page and post content from different sites, or from a locally hosted site to a production server for example.

Notes

  • The $tag for each shortcode must be unique. Which means that if another plugin has a similar shortcode, it will override yours or yours will override theirs depending on which order the plugins are included.
  • Shortcode $tag names are always converted to lowercase.
  • This function has been available since WordPress 2.5.

Comments