Navigation

How to create your own WordPress shortcodes

By Sara Vieira | Business, Web Development, WordPress | Jun 4, 2013

In version 2.5 WordPress introduced shortcodes, and all of us have probably used them at one time or another. They usually come bundled with plugins, or even themes, and what they do is watch for when you insert something inside square brackets then replace that with some other content; it could be a simple sentence or it could be a massive PHP function, it all depends on what you instructed WordPress to do.

Bundled shortcodes are great, and speed up things considerably, but wouldn’t it be great to know how to create shortcodes of your own?

In this article I’ll take you through creating some simple WordPress shortcodes to help you create any functionality you like.

 

A simple shortcode

The shortcode API works very simply: first you need to create a callback function that will run anytime the shortcode is used; then you need to tie that function to a specific shortcode making it ready for use. The code is frequently placed in the functions.php file, but if you plan on having a lot of shortcodes, it makes sense to create a separate file and include that file in your functions.php file.

In our first example we want to create a shortcode that will create some lorem ipsum every time we type [lorem] into the editor. First we need to create the callback function that will return the lorem ipsum (in shortcodes we don’t echo anything, everything is returned):

function lorem_function() {
  return 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec nulla vitae lacus mattis volutpat eu at sapien. Nunc interdum congue libero, quis laoreet elit sagittis ut. Pellentesque lacus erat, dictum condimentum pharetra vel, malesuada volutpat risus. Nunc sit amet risus dolor. Etiam posuere tellus nisl. Integer lorem ligula, tempor eu laoreet ac, eleifend quis diam. Proin cursus, nibh eu vehicula varius, lacus elit eleifend elit, eget commodo ante felis at neque. Integer sit amet justo sed elit porta convallis a at metus. Suspendisse molestie turpis pulvinar nisl tincidunt quis fringilla enim lobortis. Curabitur placerat quam ac sem venenatis blandit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sed ligula nisl. Nam ullamcorper elit id magna hendrerit sit amet dignissim elit sodales. Aenean accumsan consectetur rutrum.';
}

Next we need to add this shortcode to WordPress using the add_shortcode function in either our functions.php file or a file that’s being included in it, this function adds the shortcode and also ties it to the function we just created. add_shortcode only takes two arguments, the first one being the name we want this shortcode to have (what we will type between the square brackets) and the second one being the function we want to attach to that shortcode:

add_shortcode('lorem', 'lorem_function');

That is all it takes to create a simple shortcode in WordPress.

 

Adding parameters

Continuing with this dummy content idea, we often need images in our content when we preparing our mockups and these images need to be different sizes, so now we’ll create a shortcode to insert an image like this:

[picture width="500" height="500"]

When WordPress encounters this we want a function that will insert an image. It needs to read the width and height attributes, but just in case we’ll also provide default values so that it can be used without the attributes. Because we may not have an image available, we’re going to use the lorempixel.com service to provide us with a random image.

First we need to create the function:

function random_picture($atts) {
   extract(shortcode_atts(array(
      'width' => 400,
      'height' => 200,
   ), $atts));
return '<img src="http://lorempixel.com/'. $width . '/'. $height . '" />';
}

We named this function random_picture and since this shortcode will be able to take arguments we gave it the $atts parameter. In order to use the attributes we need two functions: the shortcode_atts which is a WordPress function that combines our attributes with known attributes and fills in defaults when needed; and the extract PHP function which, as the name suggests, extracts those attributes we set for our shortcode. Finally the function returns the value we want, in this case the HTML code for our image combined with the width and height variables.

The only thing left to do is register this shortcode:

add_shortcode('picture', 'random_picture');

Our shortcode is complete, when we type [picture] it will give us a random image 400 by 200, and if we use the attributes we can create an image of any size we please.

 

Conclusion 

Creating little shortcodes for things we use frequently definitely helps us when writing blog posts because you can do anything you please with shortcodes, it can be as simple as returning a sentence, or as complex as adding a form or the latest posts sorted by month.

 

Have you created helpful shortcodes for WordPress? What shortcodes do you wish existed? Let us know in the comments.

Featured image/thumbnail, code image via Marjan Krebelj.

Share this post
Comments (no login required)
  • http://www.coyneenterprises.org/ Coyne Enterprises

    Great tutorial, this should save me a ton of time once I build up some shortcodes for things I use the most

  • http://www.webdesignerguide.net/ Khizer Aziz

    Thank you for this totorial was looking for shorcodes with parameters…very simple and great share…

  • http://cssmatter.com/ CSSMatter.com

    nice!

  • http://seoservices4smallbusiness.com/search-engine-optimization.html Hemanth Malli

    Thanks for the time saving tip. I will try this !!

  • Since84

    Perfect Tutorial. Thank you for making it so straightforward.

  • Ysan

    Hi Sara,

    I hope to find some more information about shortcodes. I am looking for a shortcode to add the childcategories of a certain post.

    Categorie : Region
    Childcategories : Region1, Region2, Region3,…

    The text in the post would be like :
    – This activity is possible in : [regions]

    which returns the childcategories of “Region”
    – This activity is possible in : Region1, Region2

    I’m not sure if this is well written php, but this seems to work :

    function region($atts) {
    $sep = ”;
    foreach((get_the_category()) as $childcat) {
    if (cat_is_ancestor_of(27, $childcat)) {
    echo $sep.”,$childcat->cat_name,”;
    $sep = ‘ / ‘;
    }}}
    add_shortcode(‘region’, ‘region’);

    This seems to work… but it places the childcategories above the post and not inside the text (where i put the shortcode).

    Almost there… just need that little bit of help ;-)

    Kind regards,

    Y

  • Dimple Thakur

    thanx for this post

  • Dimple Thakur

    Great tutorial thanx

  • Mahesh Sangam

    i have one website where i want to add shortcodes like one full page in that float left 600px and float right 400px like that i need to make 1000px covered with this two content wrappers floating each other. i created function and called but it;s not working …

    Here is code – i added this in style.css

    #lorem{width: 96%; max-width:1255px}

    #lorem .left{width: 56%; max-width: 755px; float: left;}
    #lorem .right{width: 40%; max-width: 500px; float: right;}

    like the one you given function.php first example..

  • Deep Anandrao

    Great , Thanks for the road map , will dig dipper .

  • http://templendo.com/ Chris Brown

    Useful tutorial.

  • http://www.homeblogs.co.uk/ Homeblogs

    nice

  • Ann

    nice tutorial, thanks

  • Tauseef Abbasi

    nice share

  • http://www.fasttrackcreations.com/blog Nikhil Malhotra

    Thanks for sharing:)

  • http://www.ashtricks.com/ Ashish

    How to copy from a theme to another theme ?

  • Lou Storiale

    finally someone wrote the blog article I was searching for… saves me a lot of time. Thanks!

  • apuges

    Great!!! Thanks!! You also saved me a lot of time! ;-)

  • Jeanvaljan974

    Hi,

    Thanks for the tuto.

    Unfortunately, as a beginer, i can’t adapt it to my need which is to create a shortcode to display rss feeds. (I always have a white screen of death)

    here is the php code i’m starting with:

    The objective is to create a shortcode to display the rss of a specific blog and specify in the shortcode the blog feed URL and the number of post to display.

    It would be great if you could help me to adapt this.

    Thank you in advance!