WordPress Shortcodes: The Right Way
videos

WordPress Shortcodes: The Right Way

Tutorial Details
  • Technology: WordPress
  • Difficulty: Moderate
  • Estimated Completion Time: 20 minutes

Final Product What You'll Be Creating

One of the primary reasons why WordPress is the most popular CMS platform available is the sheer level of customizability that it brings to the table. Today, we’ll review the process of integrating one of those popular features, shortcodes, in the most user friendly way possible, into our theme.

Tutorial now on Wptuts+

A Visual Crash-Course in Shortcodes


A Word From the Author

Even though there are a few trillion options to choose from, WordPress has comfortably taken the crown as the king of CMSs and blogging platforms with its incredible flexibility. A shortcode is one of those features that ratchet up the user friendliness of the system.

However, most implementations still require you to remember the shortcode itself. When you’ve created a masterpiece of a theme, the usability shouldn’t really lag behind. I’ll show you how to create shortcodes and then integrate it with the editor itself, so the user doesn’t have to go poring through your docs just to remember the correct syntax to embed a button. Intrigued? Let’s get started right away!


What Are These Shortco-whamathingies?

It’s called a shortcode and it has been part of the base WordPress installation since it hit version 2.5. Basically, these are similar to the bbcodes used on popular message board software: lightweight markup used to format content.

Here, you can define your own codes to use within your theme. Unlike BBCodes, though, shortcodes are primarily used to shield the user from tedious markup and possible errors. By using a shortcode, for say, a button, the user doesn’t have to remember the complicated markup that needs to be input to create the button. Overall, it’s quite a boost to a theme’s usability and possibly, noob friendliness.


ShortCode Variations

If you’re unfamiliar with the concept of a BBCode, and by extension, shortcode, this is how the simplest version looks:

[my-gallery]

If you’ve ever embedded a gallery with WordPress, you’ve already used a shortcode!

There are two more variations you should also be familiar with.

 [button]Content[/button]
 
 [link to="www.net.tutsplus.com"]NetTuts+[/link]

We’ll implement each of these variations first before moving onto other, busier things.

Each shortcode implementation requires a two-step process:

  • 1: Create the primary handler method
  • 2: Hook up the handler to WordPress

Regardless of the complexity of the shortcode, the core steps remain the same.


Take 1: Replacing Strings

We’ll first learn how to implement the simplest shortcode possible. As a use case, let’s say you end each post with some common signing off text. Copying and pasting might be a simple approach, but you may feel like a luddite doing so. Let’s fix this with some WP niftiness!

Unless otherwise noted, all of the code below goes into functions.php

Step 1: Create the Primary Function

The primary function takes care of the core logic of your shortcode. We’ll need to create this first before proceeding.

 function signOffText() {
    return 'Thank you so much for reading! And remember to subscribe to our RSS feed. ';
}

Step 2: Hook into WordPress

The next step, as you may assume, is to hook into the WordPress system to associate the shortcode with this text. This is done using the add_shortcode method.

add_shortcode('signoff', 'signOffText');

Yes, a single one-liner is all it takes. The first parameter defines the shortcode you’ll be using in the editor, while the the second points to the function we created a moment or so ago.

Note: The add_shortcode method always comes after the handler method.

That should do it. Just type [signoff] into your editor and WordPress will dynamically replace the text as needed.


Take 2: Wrapping Content

Next up, we’re going to take a look at another variation: wrapping some content with some markup. You’d have to use it like so:

[quote]Some text[/quote]

Step 1: Create the Primary Function

The primary function has to be modified a little here. We’re noting that our function receives two parameters: attributes through the atts variable and the content itself through the content variable.

The next step is simply to return the markup wrapped around the selected text.

function quote( $atts, $content = null ) {
	return '<div class="right text">"'.$content.'"</div>';
}

Step 2: Hook into WordPress

This step remains the same:

add_shortcode("quote", "quote");

I like to name my shortcodes exactly the same as the primary functions unless the naming gets unwieldy. You may have your own styles so feel free to change the naming scheme. There’s no accepted best practice.


Take 3: Adding Attributes

Finally, we’re going to take a look at adding attributes to the mix as well. You’d have to use it like so:

[link to="www.net.tutsplus.com"]NetTuts+[/link]

Step 1: Create the Primary Function

The primary function needs to be refactored to handle all the new functionalities we’re bringing in. First up, we merge the attributes passed in with the shortcode and the attributes we’re expecting. You can read up more on the process here.

The final step, as always, is simply to return the markup we want after filling it up appropriately. Here, I’ve used the data sent with the shortcode to fill in the anchor’s href attribute as well as content.

function link($atts, $content = null) {
	extract(shortcode_atts(array(
		"to" => 'http://net.tutsplus.com'
	), $atts));
	return '<a href="'.$to.'">'.$content.'</a>';
}

Step 2: Hook into WordPress

This step remains unchanged, but essential. Remember, without this, WordPress has no what to do with the shortcode.

add_shortcode("link", "link");

Kicking Everything Up a Notch

This is where you’d expect this tutorial to end but no, you’ve guessed wrong. As I mentioned earlier, shortcodes take away a lot of pain, but there are few gotchas. For one, the user has to remember the shortcodes he has at his disposal to make meaningful use of them.

If you have just a couple, it’s all good, but with feature laden themes, remembering each one becomes a chore. To rectify this, we’re going to add buttons directly to the TinyMCE interface, so the user can simply click on the button to get it all done.

As an example, I’m going to teach you how to add the second variation to the editor. I’m hoping you can extrapolate this information for the specific functionality you have in mind.


Step 1: Hook into WordPress

The first step in the process is hooking into WordPress and adding our initialization code. The following snippet takes care of that. Remember, all of this needs to be in your functions.php file.

 add_action('init', 'add_button');

We’re asking WordPress to run the function called add_button when the page is initially loaded. add_action is our hook into WordPress’ internals.


Step 2: Create Our Initialization Function

function add_button() {
   if ( current_user_can('edit_posts') &&  current_user_can('edit_pages') )
   {
     add_filter('mce_external_plugins', 'add_plugin');
     add_filter('mce_buttons', 'register_button');
   }
}

This tiny snippet of code will be executed when the page loads. Above, we’re checking whether the user has the necessary authorization to edit a page or a post before proceeding.

Once that’s done, we hook up two of our [to be written] functions to specific filters. Both of these actually hook into TinyMCE’s front end architecture through WordPress. The first is executed when the editor loads the plugins while the second is run when the buttons are about to be loaded.

In the example above, we proceed regardless of which mode the editor is in. If you want to display it only when the editor is in, say, visual mode, you’ll need to perform a quick check. If get_user_option('rich_editing') evaluates to true, you’re in visual mode. Otherwise, HTML mode. I typically tend to add these buttons only under visual mode but feel free to mix and match here.


Step 3: Register Our Button

function register_button($buttons) {
   array_push($buttons, "quote");
   return $buttons;
}

The function merely adds our shortcode to the array of buttons. You can also add a divider between your new button and the previous buttons by passing in a | before.


Step 4: Register Our TinyMCE Plugin

function add_plugin($plugin_array) {
   $plugin_array['quote'] = get_bloginfo('template_url').'/js/customcodes.js';
   return $plugin_array;
}

The snippet above lets TinyMCE, and WordPress, know how to handle this button. Here, we map our quote shortcode to a specific JavaScript file. We use the get_bloginfo method to get the path to the current template. For the sake of organization, I’m keeping my tinyMCE plugin along with my other JS files.


Step 5: Write the TinyMCE Plugin

Now onto the final portion of our endeavour. Remember, the following code goes into a file called customcodes.js placed in the JS directory of your theme. If you thought it went into functions.php like all the code above, no cookie for you!

(function() {
    tinymce.create('tinymce.plugins.quote', {
        init : function(ed, url) {
            ed.addButton('quote', {
                title : 'Add a Quote',
                image : url+'/image.png',
                onclick : function() {
                     ed.selection.setContent('[quote]' + ed.selection.getContent() + '[/quote]');

                }
            });
        },
        createControl : function(n, cm) {
            return null;
        },
    });
    tinymce.PluginManager.add('quote', tinymce.plugins.quote);
})();

Looks a little complex but I assure you, it’s anything but. Let’s break it down into smaller section to make it easier for us to parse.

First order of the day is a quick closure to keep from polluting the global namespace. Inside, we call the create method to create a new plugin passing in the name and other assorted attributes. For the sake of brevity, I’m just going to call my plugin quote.

Once inside, we define the init function that’s executed upon initialization. ed points to the instance of the editor while url points to the URL of the plugin code.

Most of the attributes should be fairly self explanatory. Note that the image you pass in is relative to the parent folder of the JS file that holds the code. Here it’d be theme directory/js.

Next up, we create the event handler for this button through the onclick function. The one-liner it contains essentially gets the selected text, if any, and wraps it with out shortcode. setContent and getContent are helper methods provided by tinyMCE to manipulate the selected text.

Finally, in the last line, we add the freshly created plugin to tinyMCE’s plugin manager. Pay attention to the names you’re using in each step. It’s error prone if you’re not paying attention. And that’s about it! We’re done! Load up the editor and make sure your spiffy new button is working.

Tutorial Image

Conclusion

And there you have it. We’ve successfully integrated shortcodes into a WordPress theme in a very user friendly manner. Hopefully you’ve found this tutorial to be of help. Feel free to reuse this code elsewhere in your projects and chime in within the comments if you need any assistance.

Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding and thank you so much for reading!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://laroouse.com esranull

    very usefull post thanks a lot

    • http://zlatan@onioneye.com OnionEye

      Reading nettuts’ posts every day – free
      Obtaining a premium membership at nettuts – $9
      Watching you always place a comment first on almost every nettuts post, while using a gravatar of a sexy chick – Priceless

      • http://digitalrenewal.com Trisha

        haah, right? The site isnt there anymore, so I guess we’ll never know. Great tutorial by the way, just from watching the video, im finally starting get this stuff. Its amazing how much you can do without knowing a lick of code… I could rule the world if I actually knew the language(s). and thanks for that extra step, the tinymce inclusion… I want the cookie!

  • aleks

    i saw esranull’s picture and forgot what i was about to comment…

    • http://www.ssiddharth.com Siddharth
      Author

      Smooth, dude.

    • http://ivorpadilla.net Ivor

      @Aleks hahaha me too dude.

    • http://jamiebrewer.com Jamie

      I don’t think it’s even a girl. I think it’s someone wanting people to click and visit their website.

      • Dutch

        Yeah, I dislike people who act like that (submit a comment while using a picture of a girl to let more people click). Especially when they comment on every post with useless words. When you visit the site, you’ll see the name of that person: Osman. That’s a Turkish name for a boy.

  • http://mikhailkozlov.com Mikhail Kozlov

    1 month too late as usual :), but great post none the less. Now would have to go back and review my implementation.

  • http://www.psdtomagento.org PSD to Magento Services

    That was a great tutorial Sid!
    Im just working on our official site and wanted to add some shortcodes for the guys, who have to add blogs and posts eevery day and this has saved my life!
    Will go try tomorrow morning. Thanks again for writing that good.

  • Luke

    This is great stuff and I have been doing this for sometime. However, how do you get a shortcode to show up in the “HTML Editor” side of the TinyMCE?

    • Steve

      I, too, would very much like an answer to this. I’m not an especially big fan of the ‘Visual’ editor.

    • http://newarts.at Drazen Mokic

      He mentioned it but anyway you can do it like this

      if ( ! get_user_option(‘rich_editing’) )
      {
      … code here wil only be executed if user is NOT in visual mode, so he is in HTML mode …
      }

      Probably there is something like ‘html_editing’ too but i am not sure what it is called exactly.

  • Lukas

    Drupal ftw!

  • http://www.wordimpressed.com Devin Walker

    So many people think ShortCodes are the hard to implement, but in reality they are really easy!

  • http://domakas.com/ Domas Makšimas

    Well, that’s useful..

    However, I would like to see, how you can fight default WordPress formating when using shortcodes like

    Piece of code

    . How would you disable those <p>’s and <br>’s?

  • http://contempographicdesign.com Chris Robinson

    Awesome tut, been looking for a TinyMCE tut like this for quite sometime!!

    • http://wizylabs.com WizyLabs

      Same Here

  • http://contempographicdesign.com Chris Robinson

    Would love to see some example code with multiple buttons registered.

    • http://contempographicdesign.com Chris Robinson

      Never mind got it figured out!

      • Juho

        Mind to tell how you did? I cant get it to work! It’s way to mutch work to copy everything and change all the names. There must be an easier way?

      • http://hassanonodesk.redillusion.com/ Hassan Mehmood

        Please can you Show us how you did that??? =)

      • http://dashaluna.com Dasha

        Hello,

        Can you please share with us how to manage multiple shortcodes and buttons in the editor. :) I’ve seen lots of people were asking how to do it, but no reply.

        Many thanks,
        Dasha

        P.S. great tutorial, thanks a bunch! :)

        • Arg Geo

          This is how you add multiple buttons. Worked for me, hope will work for you too.

          <?php function warning( $atts, $content = null ) {
          	return 'WARNING '.$content.' ';
          }
          add_shortcode("warning", "warning"); ?>
          
  • Dennis

    I have recently spent lots of time into working on something like this and had to read really lots of documentation and collect small pieces of tutorials in order to accomplish what I needed.

    I’m sure this post will be very helpful and save lots of time to many people :)

    • http://www.ssiddharth.com Siddharth
      Author

      Good to know this was of help. Thanks for reading!

  • http://jacobdubail.com Jacob

    Thanks for the tutorial and video! Just what I was after.

  • chris

    nice tutorial, is this downloadable for tuts plus members? (the code)

  • http://www.uxdesign.fr Alexandre HOCHART

    Couldn’t expect more accurate. Thanks Siddarth.

  • z_kagenotora

    This is really good! Thanks!

  • http://contempographicdesign.com Chris Robinson

    How would one go about having the buttons inserted into another row in the toolbar? Currently they’re all added to the first row, so it doesn’t work so well once you get a few in there if the user is working on a smaller resolution.

    • http://contempographicdesign.com Chris Robinson

      Scratch that, figured it out.

      Changed:

      add_filter(‘mce_buttons’, ‘register_button’);

      to

      add_filter(‘mce_buttons_3′, ‘register_button’);

      • http://www.ssiddharth.com Siddharth
        Author

        You keep answering your questions without giving us a chance.

      • http://www.ssiddharth.com Siddharth
        Author

        I missed a smilie there. :(

        But yep, most of the questions can be answered by a few minutes of playing around with the APIs. It’s really intuitive.

        Thanks for reading, mate!

  • Brad

    Great Tut…

    When you create the button in the visual editor for the shortcode though I seem to lose the ability to add variables to the short code.

    For example I created variables for title, sub title, body text etc and they all work fine with the first methods. But as soon as I create the button for the visual editor the only thing that is passed to the shortcode is the text that has been selected as I am no longer typing out “title=bla bla” and “subtitle=”whatever”… how can my users have the option of filling in these variables when they click the button?

  • Brad

    FYI I mean like the other buttons in the visual editor that have small forms pop up when you click them… like the link button.

  • arnold

    Thanks for the tutorial, love the screencast & the text version..very informative
    by the way guys can you update the tut about wordpress as cms …

  • http://khrrsn.com khrrsn

    my question is how would you set it up in tinymce so that when you click on it, you get a popup and you can input maybe 3-4 inputs and select insert and it generates that code for you?

    • Vasya

      Yes, that would be perfect!

    • Brad

      Exactly what I need to know…

    • http://www.ssiddharth.com Siddharth
      Author

      You hook into the onclick method. In my technique, I’m merely editing the selected text. You could create a quick modular form when it’s clicked and go from there.

      If enough people show interest, look for a follow up tut on this.

      Thanks for reading.

      • http://khrrsn.com khrrsn

        That’d be awesome, I spent a good amount of time yesterday trying to figure it out, and I never got it to work.

      • http://contempographicdesign.com Chris Robinson

        Would also be interested in this!

      • Brad

        That would be awesome.

      • http://www.ssiddharth.com Siddharth
        Author

        Good to know! Look for a follow up in the future :)

      • http://themeforest.net/user/DDStudios Guilherme – DDStudios

        To insert the pop window you need to create an open event in yoru javascript.

        The pop up has nothing to do with php.

        The inputs are all managed through javascript itself.

        It’s rather complicated and hard to explain in one reply. You can create tabs and all that too. I’d suggest further reading on tiny_MCE plugins documentation (which isn’t that great btw) and downloading some plugins that have it included so you can take a look at their code.

      • http://ryanfred.com ryanfred

        Just curious :-)
        Any chance of that tut on creating a quick modular form to help users construct shortcodes??

        This would be a very timely and helpful follow up to this tut.

        Thanks – hope all is well!

      • Matthew

        +1 on needing a hand-holding walkthrough on adding a pop up that lets you select from multiple shortcodes – then insert the selected shortcode in the editor.

        • zargaye

          Thanks for the review Pippin, Im hulbemd with your comments and really appreciate your suggestion! It’s great to have this type of feedback.It’s no surprise you have this feeling about CSS (which also could be Javascript or asset images) I must have went a hundred times around my head about this matter! yet I can’t make up my mind of where I stand on this, I came to realize it’s a grey area where different users have different needs. Some want to have shortcodes look and behave the same across all themes and some wants them to be different. Since I have yet not decided if the plugin should take a side, for now the approach has been to leave the decision open for the users to decide. This post however really encourages me to keep thinking it over till I find an appropriate solution that could fit both worlds elegantly. Definitely don’t discard the possibility that it becomes a feature in the near future Thanks again for such a nice review and hats off for your awesome plugins!Kind Regards!

    • http://amayamedia.com Rene Merino

      Still waiting on that modular form window for shortcodes.

  • http://www.artrevolt.hr Revolter

    Code from video has some error to me……don’t know way?

    This is a code I modified:

    function video_embed_func($atts) {
    extract($atts = shortcode_atts(array(
    ‘src’ => ”,
    ‘width’ => 600,
    ‘height’=> 338,
    ‘title’ => ‘The Video’,
    ), $atts));
    return ‘

    ‘ . $atts['title']. ‘
    ‘;
    }
    add_shortcode(‘video_embed’, ‘video_embed_func’);

    • Kevinsturf

      I think you’re using the wrong quote for the line with src in it.
      Try this: ‘src’ => ‘ ‘ ,

      use single quotes.

  • South Indian :)

    Thanks for your post :-)

  • http://www.github.com/jas- Jason Gerfen

    Thank you for this..

  • http://www.colordeu.es/BLOG COLORATE

    Simply, excellent

  • http://www.fenotype.nl Lourens

    Thanks a lot, I’m so going to use this in my next theme :)

  • http://www.chrizzle.nl Chris

    Wow Thanks! I was looking how they did it on psd.tutsplus and i made a div & styled it but; i pasted the whole <div class="tutorial_image="..blabla into the post itself. Im glad i found this before i did even go further! this would save me alot of time, its easier and even shorter in posts!

    Im deffo gonna recommend this!
    Thanks, Chris

  • http://www.johnejohnson.org John Johnson

    Great video! Jeff, I’m curious as to what program your using that adds the black bar on the right-bottom hand side of your screen that changes depending on what main window you have open with different options?

  • Kristof

    Great tutorial – thanks.

    Only problem with using shortcodes, or even php includes for that matter, is they’re not mobile friendly. On a mobile browser, the shortcode text is displayed instead of the actual content. Do you know of a way around this?

  • http://www.smick.ne smick

    WordPress is awesome, but for this kind of functionality, MODX CMS does this so much more easily.

    WordPress REALLY should create an interface for this to store them and have an admin popup page to refer to them.

    I’d like to see a few standard snippets added to wordpress by default too. Google, Yahoo, other maps, Video embeds rom youtube, vimeo, and a couple others. Flash content. Share this content. I coudl think of a few others.

    I’m not sure how it affects performance, but it seems like adding a ton of stuff to function.php gets to be inefficient after a while.

  • http://www.iwebgallery.com iwebgallery

    Always good post

  • http://www.chrizzle.nl Chris

    I got a question, it worked fine on localhost but when i uploaded it to my host i get errors :S my host accepts php 5.2

  • http://www.redmoskito.de Roland Mücke

    Thanks a lot! Very useful and funny written article. I want more! ;-)

    Roland

  • http://atinder.com atinder

    thanks a lot you made my day.

    I was looking for this

  • http://www.ucarmetin.com Metin

    Hej Siddharth, thanks for the useful quality tips you shared with us in this tutorial. Thumbs up!

    I wonder are you planning to create a screencast on developing wordpress widgets? If you could, that would be great.

    Cheers!

    • http://www.ssiddharth.com Siddharth
      Author

      Sure, I’ll add it to my list. :)

      Thanks again for reading!

  • http://theaggressive.com Shawn

    This would make it much easier to code up posts. Make shortcodes for common markup and plugin where needed.

  • http://www.mylittlenepal.com Avinash

    Great tutorial!
    I’ve been looking for this thing.

    Thanks,

  • David

    I really like the good explanation.. i wish jeff cover more in depth the Write the TinyMCE Plugin, which i think it’s good to know, any way.. good job keep it up!

  • http://themeforest.net/user/DDStudios Guilherme – DDStudios

    Great tut mate!

    I wish you had released it sooner.

    Had to spend days trying to get my buttons to work on my themes because the documentation on tiny_MCE is really poor. Not only on plugins but the overall documentation is not that good.

    Keep up the awesome work.

  • http://www.searchengineoptimisationseo.co.uk/ Ken Davies

    Great tutorial, thank you! WordPress is my favourite blog/CMS platform and shortcodes are a great way to personalise the deisngn.

  • http://www.acuterays.com Acute

    Great step by step and easy to understand tuts. Love every tutorials fron netTuts. Keep rocking

  • http://www.creativevisualdesign.com Chad

    Take 3: Adding Attributes example breaks. Anyone else experiencing this?

    This code:

    add_shortcode(“link”, “link”);
    function link($atts, $content = null) {
    extract(shortcode_atts(array(
    “to” => ‘http://net.tutsplus.com’
    ), $atts));
    return ‘‘.$content.’‘;
    }

    with this shortcode: [link to="www.net.tutsplus.com"]NetTuts+[/link]

    doesn’t work for me.

    Any suggestions.

    • http://www.creativevisualdesign.com Chad

      To follow up on my prior comment, the first two examples worked just fine but as soon as I did the third example it broke the site. I feel that something in the code might be off in the example like a ‘ or ” because I copied it as plain text and inserted into the functions.php file while adding the shortcode on the wp page on the html tab.

      Thanks for any assistance.

    • http://twitter.com/mStudios mStudios

      the closing [link] in the tutorial is missing the closing slash. it should be [/link] – not only on step 3 but also on top, in the overview on options on how to use shortcode.

      • http://wp.tutsplus.com/ Japh

        Thanks for pointing that out @twitter-7359052:disqus. This is a *very* old post! I’ve fixed the error you pointed out now though.

  • http://www.jasonnugent.com Jason

    My client is using IE 8 in Quirks mode and the tinyMCE.PluginManager errors out and won’t show the editor additions. As I look into a new solution has anyone else run into this particular issue? Do you have an update?

  • http://sideradesign.com paul

    If you don’t want to mess with code, this plugin does it for you : http://wpstorm.net/wordpress-plugins/post-snippets/

  • Alice

    Not working for me… The shortcode works, but the button in the tinymce editor doesn’t show up. What could be the most likely error one could have? No error messages show up.

  • http://benstockdesign.com Ben Stock

    Siddharth, this post (and all of your others) are well-written, easy to follow, and are of the utmost quality. I just wanted to let you know that I appreciate what you do. Thanks a lot man!

    • http://www.ssiddharth.com Siddharth
      Author

      Any time! Glad this was of help to you. :)

  • Chris

    Thank you VERY much for the detail tutorial! I do have one important question though which NO ONE seems to be able to answer.

    I would like to find some simple way of automatically replacing any specific shortcode with an image for example so within the admin visual editor such a shortcode would show up like the gallery does.

    Can you PLEASE PLEASE PLEASE explain to me how this can be done?

  • http://graphicarmory.com Matthew Simmons

    Looks like I’m late to the party. Great article and video though. =D

    RT’d

  • http://graphicmuse.com jan

    Thank you so much for posting! I was able to add the button to the visual easily, just wondering now how to add several to the html editor, but as text buttons, but images. ElegantTheme’s usually have these and I find them so useful.
    below is a link to what I’m trying to do. Thanks!

    http://www.flickr.com/photos/graphicmuse/5416346721/

  • http://www.abhijit.biz WordpressArtist

    Its an awesome tutorial. Indeed it will help us while designing new themes in WordPress. Thanks for sharing.

  • http://www.jmonit.com Monit

    Hi Siddharth

    Very nice tutorial. I like your tuts. I have a query regarding shortcodes.

    How can we make the buttons so that they execute the function instead of just adding the shortcodes around the selected text.

    For example: Is there a way to change plain list into a list with image as a bullet, with one single button click. So that the user can actually see the change in the editor.

    Monit

  • http://joshbryan.me Josh

    My first comment on netTuts, but I’m not exactly a newbie. While gazing upon all of my grey hair this morning, I informed my wife that I was no longer the computer whiz kid…. then I remembered I never was, lol.

    I must say, this site makes me very happy. It’s one of the reasons I love working with computers so much, there is always something new to learn.

    I was a Joomla nut for the past 5 years but have recently been falling more in more in love with wordpress. This article is just a prime example of why I love wordpress so much. It is such a fun system to work with.

  • El garch Hicham

    I was lookin’ for this post helped me to understand the add_shorcode atttibutes.
    Thanks a lot :D

  • http://rafalboro.pl KaGe

    Exactly what I was looking for!
    Thanks!

  • http://www.blazingmoon.org Andy

    Completely awesome. Thanks so much for posting this.

  • http://farmboyinc.com Jason McArtor

    Great tutorial, but I’m unable to get the buttons to display in TinyMCE–in fact, all of the Visual Editor buttons disappear. I never used this prior to installing WP3.1 and it appears there may be a bug of some sort that is affecting TinyMCE. Is there a fix to get this to work in WP3.1?
    Thanks!

    • http://intrepidrealist.com Alicia St Rose

      Hi Jason,
      I was having the same problem. If you are adding this to a child theme then you have to change “template_url” in step 4 to “stylesheet_directory”.

      Hope that helps!

  • john

    I have a question…..If you have a plugin can you add the php to the functions php of the them to have it permanently a part of the theme?

    Is it a little more than copy paste?

  • http://www.johnejohnson.org John

    Awesome tutorial Siddharth! For those interested, I also have a video tutorial dealing with WordPress shortcodes. http://www.johnejohnson.org/tutorials/wordpress-custom-shortcodes-creating-a-media-box/

  • Ron

    Great tutorial and a great site!

    As the code is, it works good. I have it implemented into one of my plugins for styling blocks of text.
    I do have a few questions on it though. I’m not sure if 3.1 changed anything or what…

    1) After the post is published it displays fine on the page, but the shortcodes still show in the visual editor, is this normal?

    ie: [graybox]This is a gray box[/graybox]

    2) Since my plugin only deals with pages and not posts, how can I limit it to the Page editor only?

    3) I’ve added 5 buttons. I repeated the whole js code for each one, is that right or is there a simpler way?

    Thanks!

  • http://cyberchimps.com Tyler

    I seem to be having trouble using this method to handle multiple shortcodes and buttons, does anyone have any good references for this?

  • yetimade

    So, thanks for writing this article. But, am I missing something?

    I’m trying to do the Wrapping Content short code, but for whatever reason, it’s not working.

    I’m not too familiar with how these look, so maybe a final version would be good? I just don’t know where this stuff goes necessarily.

    Thanks
    JC

  • http://www.pushplaybang.com paul

    Hey there – thanks – great tut, also looking for a way to add it to a quick form popup of some kind…. I’ve implemented a couple of shortcodes including a column and dynamic button shortcodes and would be great to have all the variations come up in a drop down menu or be selectable some how…

    thanks again… exactly what I was looking for (almost :))

  • http://intrepidrealist.com Alicia St Rose

    This tutorial is awesome. I’m delighted with how cool my new button looks and the ease of use for my client!
    Thank you!

  • http://www.jiudesign.be/ Intégrateur Wordpress

    Thank you for this usefull tuts.
    But it can be usefull to create a list of shortcode instead of many icons in the tiny mce.

  • http://thedevelopertuts.com Sebastian B

    Interesting tutorial, it really helped me on a blog i’m doing, thanks.

  • http://unrelatedmedia.ca Neil

    Hey guys.

    Great tutorial! I love nettuts for their quality.

    Something I think a lot of the tutorials for adding a custom TinyMCE button in wordpress is the creation of multiple buttons. In response to how much I hate copying and pasting code that basically does the same thing I’ve created a class to do it for me.

    What does this mean?

    It takes tutorials (most on the web seem identical to this one) and puts all the wordpress-specific functions into a class file. This means that I can now use the predefined class, create a copy of it and feed it the basic variables I need to create a button.

    The javascript is still independant files, but it was a quick tutorial in response to an article by Justin Tadlock.

    So long as you instantiate the class for each button (copy it) you can create as many buttons as you like, easily. Just be sure to make a 20×20 pixel image for each button and a unique javascript file for each one.

  • Shawn

    I could not disagree more. I think that shortcodes, though good for the theme designer, are becoming extremely problematic and overused for the end-user. In essence, a site written with an abundance of shortcodes “locks” in the content to a specific theme or designer, effectively negating everything that WordPress is intended for. Themes should be nothing more that display engines, and primarily should be for the design of the site. There is certainly a place for shortcodes, especially when referring to difficult items such as galleries or portfolios. But for simple HTML, a user should just use that, or better yet, as some of the commenters mentioned, be left to a plugin so that the user is free to switch themes if they wish….otherwise what was once a beautiful button will become nothing more than [button]Read more[/button]

    • Lauren

      Interesting point about the shortcodes locking folks into a particular theme. I hadn’t considered that… Thanks for pointing it out :)

  • hippop

    hoyyiggigi

  • http://www.newwordpresstheme.net/ minhkevin

    I installed fishpig with magento. But it doesnot support shortcode. Show please tell me how to add directly to wordpress theme. And anyway to do it. I am using survey plugin. Thanks!

  • http://www.tecnofagia.com Tecnofagia

    Awesome! I’m using this code to insert QRCodes in my posts (with Super Cool QRCode plugin) and it worked like a charm. Nettuts+ rocks.

  • Jacob

    Great tutorial. Just what I was looking for. When I try to add the javascript to a WP 3.2 install, I get an error: “tinymce is not defined”. Is the API different for WP 3.2?

  • http://www.daveismyname.co.uk Dave

    Excellent tutorial, I found it easy to follow and implement, like others have said I’d be interested in adding pop functionality seems the most logical next step.

  • http://dave@xjsfl.com Dave Stewart

    Wicked tutorial!

    I solved my problems within minutes of watching this. Thanks very much.

  • http://8tar.com Steve Finch

    Did a google search and lucked into this post. It’s exactly what I was looking for. I have a few rather complicated shortcodes I want to add to my theme, and this will get me on my way. Thanks a lot mate.

  • http://jpine.co.uk James

    You absolute genius.. :P thanks, life saver!

  • Ben Murphy

    Disappointingly isn’t working. Experiencing what others seem to be also, all of the visual editor buttons are disappearing. If I remove the last add_plugin function I seem to simply stuff up any other custom buttons (in my case, a next gen gallery one) but the rest remain unharmed. I might guess that the get_bloginfo(”template_url’) line has something to do with it, being outdated. However even changing it out for bloginfo(‘template_directory’) or get_bloginfo(‘template_directory’) or get_bloginfo(‘stylesheet_directory’) or some such variant hasn’t seemed to help. I’m guessing this needs to be updated for < WP 3? I would love to see this.

  • http://www.summertreedesigns.com Mark

    Hi guys, help ;o(
    I am getting so frustrated because I can get the simple “sayHello” short code to work fine. But when I try to add my own function I get nothing but errors.
    Parse error: syntax error, unexpected ‘(‘, expecting T_STRING in /hermes/web07/b2615/moo.reidwebservicesca/cjmac2011/wp-content/themes/13Floor/epanel/shortcodes/shortcodes.php on line 242

    Here is my code: the “function($atts) is line 242. What am I doing wrong?

    add_shortcode(‘flexframe’, ‘flexframe’);
    function($atts)
    {
    $atts = shortcode_atts(
    array(
    ‘src’ => ”,
    ‘witdh’ => ”,
    ‘height’=> ”,
    ‘alt’ => ”
    ), $atts);

    return ‘
    ‘;
    });

    • http://www.summertreedesigns.com Mark

      add_shortcode(‘flexframe’, ‘flexframe’);
      function($atts)
      {
      $atts = shortcode_atts(
      array(
      ‘src’ => ”,
      ‘witdh’ => ”,
      ‘height’=> ”,
      ‘alt’ => ”
      ), $atts);

      return ‘
      ‘;
      });

  • http://www.summertreedesigns.com Mark

    Sorry last try here is the code:

    add_shortcode(‘flexframe’, ‘flexframe’);
    function($atts)
    {
    $atts = shortcode_atts(
    array(
    ‘src’ => ”,
    ‘witdh’ => ”,
    ‘height’=> ”,
    ‘alt’ => ”
    ), $atts);

    return ‘
    <img class=”mjflexframe”
    src=”‘ . $atts['src'] . ‘”
    width=”‘ . $atts['width'] . ‘”
    height=”‘ . $atts['height'] . ‘”
    alt=”‘ . $atts['alt'] . ‘”

    />’;
    });

    • http://duepayer.com duepayer

      Mark,

      To be clear, I’m a noob but I think I know what’s happening here. It looks like you created an anonymous function but referenced the function named flexframe in the add_shortcode function. So basically you were referencing a function that doesn’t exist. I think that naming your function flexframe will resolve the issue. Try this…

      add_shortcode(‘flexframe’, ‘flexframe’);
      function flexframe($atts)
      {
      $atts = shortcode_atts(
      array(
      ‘src’ =&gt ”,
      ‘witdh’ =&gt ”,
      ‘height’=&gt ”,
      ‘alt’ =&gt ”
      ), $atts);
      return ‘
      &ltimg class=”mjflexframe”
      src=”‘ . $atts['src'] . ‘”
      width=”‘ . $atts['width'] . ‘”
      height=”‘ . $atts['height'] . ‘”
      alt=”‘ . $atts['alt'] . ‘”
      /&gt’;
      });

  • http://duepayer.com duepayer

    my bad, hopefully this works.

    add_shortcode(‘flexframe’, ‘flexframe’);
    function flexframe($atts)
    {
    $atts = shortcode_atts(
    array(
    ‘src’ = &gt ”,
    ‘witdh’ = &gt ”,
    ‘height’= &gt ”,
    ‘alt’ = &gt ”
    ), $atts);
    return ‘
    &lt img class=”mjflexframe”
    src=”‘ . $atts['src'] . ‘”
    width=”‘ . $atts['width'] . ‘”
    height=”‘ . $atts['height'] . ‘”
    alt=”‘ . $atts['alt'] . ‘”
    / &gt’;
    });

    • http://www.summertreedesigns.com Mark

      Thanks guys, but as it turned out the theme I was using had some very funky short code programming so I copied what they did and modified it until it worked right. Thanks for all the help.

      I’ve got another project now where I’m trying to get users to see login fields on my home page using this script here http://www.wprecipes.com/add-a-login-form-on-your-wordpress-theme/comment-page-1#comment-70368

      and it works great if I put that script in my template files like home-page.php

      But if I try to put in a short code it breaks the whole site including the admin area.

      Is this what it should look like?

      <?php
      add_shortcode('clientlogin', 'clogin');
      function clogin()
      {
      return '

      Login
      <form action="/wp-login.php” method=”post”>
      <input type="text" name="log" id="log" value="” size=”20″ />

      Remember me
      <input type="hidden" name="redirect_to" value="” />

      <a href="/wp-login.php?action=lostpassword”>Recover password

      Logout
      <a href="”>logout
      admin

      ‘;
      }

  • http://cairnsdiveadventures.com Cairns Diving

    Is there anyway you can make a shortcode display a different way in the editor, say like the gallery shortcode displays the box with image. What I am trying to do is create a shortcode like [right_column]some stuff[/right_column] and that will show the content in a nice right column in the html editor?

  • Mark

    I did it again, here is the code, is this what it should look like?

    <?php
    add_shortcode('clientlogin', 'clogin');
    function clogin()
    {
    return '

    Login
    <form action="/wp-login.php” method=”post”>
    <input type="text" name="log" id="log" value="” size=”20″ />

    Remember me
    <input type="hidden" name="redirect_to" value="” />

    <a href="/wp-login.php?action=lostpassword”>Recover password

    Logout
    <a href="”>logout
    admin

    ‘;
    }

  • Mark

    ok the prename is not working here for php so just look at the script on the page http://www.wprecipes.com/add-a-login-form-on-your-wordpress-theme/comment-page-1#comment-70368

    it looks exactly like that pretty much, only contained within a div.

    Login
    <form action="/wp-login.php” method=”post”>
    <input type="text" name="log" id="log" value="” size=”20″ />

    Remember me
    <input type="hidden" name="redirect_to" value="” />

    <a href="/wp-login.php?action=lostpassword”>Recover password

    Logout
    <a href="”>logout
    admin

  • Mark

    Am I pasting this wrong?

    <?php if (!(current_user_can(‘level_0′))){ ?>
    <h2>Login</h2>
    <form action=”<?php echo get_option(‘home’); ?>/wp-login.php” method=”post”>
    <input type=”text” name=”log” id=”log” value=”<?php echo wp_specialchars(stripslashes($user_login), 1) ?>” size=”20″ />
    <br />
    <input type=”password” name=”pwd” id=”pwd” size=”20″ />
    <br />
    <input type=”submit” name=”submit” value=”Send” class=”button” />
    <p>
    <label for=”rememberme”><input name=”rememberme” id=”rememberme” type=”checkbox” checked=”checked” value=”forever” /> Remember me</label>
    <input type=”hidden” name=”redirect_to” value=”<?php echo $_SERVER['REQUEST_URI']; ?>” />
    </p>
    </form>
    <a href=”<?php echo get_option(‘home’); ?>/wp-login.php?action=lostpassword”>Recover password</a>
    <?php } else { ?>
    <h2>Logout</h2>
    <a href=”<?php echo wp_logout_url(urlencode($_SERVER['REQUEST_URI'])); ?>”>logout</a><br />
    <a href=”http://XXX/wp-admin/”>admin</a>
    <?php }?>

    or

    <?php if (!(current_user_can(‘level_0′))){ ?>
    <h2>Login</h2>
    <form action=”<?php echo get_option(‘home’); ?>/wp-login.php” method=”post”>
    <input type=”text” name=”log” id=”log” value=”<?php echo wp_specialchars(stripslashes($user_login), 1) ?>” size=”20″ />
    <br />
    <input type=”password” name=”pwd” id=”pwd” size=”20″ />
    <br />
    <input type=”submit” name=”submit” value=”Send” class=”button” />
    <p>
    <label for=”rememberme”><input name=”rememberme” id=”rememberme” type=”checkbox” checked=”checked” value=”forever” /> Remember me</label>
    <input type=”hidden” name=”redirect_to” value=”<?php echo $_SERVER['REQUEST_URI']; ?>” />
    </p>
    </form>
    <a href=”<?php echo get_option(‘home’); ?>/wp-login.php?action=lostpassword”>Recover password</a>
    <?php } else { ?>
    <h2>Logout</h2>
    <a href=”<?php echo wp_logout_url(urlencode($_SERVER['REQUEST_URI'])); ?>”>logout</a><br />
    <a href=”http://XXX/wp-admin/”>admin</a>
    <?php }?>

  • thirtyjin

    Good, I like it very much!

  • http://amayamedia.com/ Rene Merino

    Nice tutorial, but I’m having some troubles, I managed to add more buttons but they stack on top of each other, how to I pushed them to the side, the tutorial says “You can also add a divider between your new button and the previous buttons by passing in a | before.” but where do I add ” | “?

    Thanks

  • http://amayamedia.com/ Rene Merino

    Never mind I got it, was didnt edit my code right :)

  • http://www.gabsoftware.com/ Gabriel

    Exactly what I was looking for! After some research, I thought it would be more difficult to add such a button. Some people even say it’s not possible without editing the WordPress core files. Hopefully they were all wrong. I can now add buttons for my shortcodes :)

    If someone knows of a good tutorial for generating a shortcode from a modal box (especially, generating attributes automagically depening on user input), that would be awesome to share it.

    Thanks to the author of this tutorial. Well written, well explained, straight to the point, and error-free.

  • http://www.d2tstudio.com derry

    Nice article, thanks. Had to figure out myself, though, that the link “$to” in the function call was a default value… confused me for a while.

    Thanks!

  • Mostafa

    Very thanks… nice tuts.

  • http://pawel-nowak.com Paweł Nowak

    Hej :)

    Can you tell me what are you using to display the code function?

    I was searching in your source code and it’s not a plugin only css style.

    Is that right? Can you tell me how can I do that and give me a piece of this code?

    Thanks a lot ;)

  • Ignacio

    Uohhh. This is great!!

    Now, if anyone wants to add a popup with a form when clicking the new button at TinyMCE, just folow this tutorial:

    http://www.garyc40.com/2010/03/how-to-make-shortcodes-user-friendly/

    I have just tested it and is working. I’ve discovered a new world.

  • http://www.azwananuar.com azwan anuar

    That was a great tutorial Sid!
    very usefull post thanks a lot… :)

  • http://jadwal-training.com Jadwal Training

    Very usefull post.. Thanks! :)
    I will try…

  • http://ideajunction.co.uk Dan

    Thanks man. This was really helpful. Demystified the entire thing for me in 10 minutes!

  • http://www.boulouayz.com Brahim BOULOUAYZ

    Thanks for that very helpful tutorial.

  • http://www.dailyads.com.pk Adeel Abbas

    Thanks alot man its very useful, worked great, need little bit help in making it more usefull in the way of showing shortcode in dropdown if possible, as far as i figured it out we need alot css to work with to achive this, can anyone help,

    TIA.

  • http://drummerboyhosting.com Catholic Web Hosting

    Is there a sample file to reference? I’m a bit confused as to how to add more than one button. Do you have to create steps 1-5 from “Kicking It Up a Notch” for every button you want to register? Clarification would be greatly appreciated for this noob! By the way this was a VERY USEFUL POST! Thanks!!!

    • nicky

      i’m in the middle of nowhere, i jus know a little bit php and some other languages. i want to implement short codes, WHERE DO I START?

  • Horus Acosta

    one question, what if i want 5 buttons, do i have to write the js function 5 times?? is there a better way to register 5 buttons in one function, thanks in advance.

  • Lars Inge Holen

    I have made my own theme and it can’t handle shortcodes. If I follow this example or do others, the only thing that show on the page is the shortcode ( [sayHallo] ) Is there something I can do to check my site…?

  • http://avalaunchmedia.com/ Brandon Buttars

    Great tutorial. I’m excited to jump on the shortcode band wagon.

  • mattrock1

    Never too late for a kudos…. thanks for the great tutorial! *high-five*

  • http://www.etatvasoft.com/php-web-services/wordpress-development.php AliBarker

    Exciting factor about the shortcodes securing people into a particular concept. I hadn’t regarded that… Thanks for directing it out.

  • Gabriel Goga

    Nice tut and a right code.

  • OP

    Thanks for this tutorial. I was able to add a custom button in Tinymce and it works as intended.

    **HOWEVER** Perhaps I misunderstood the full effect of adding a custom shortcode to the Visual editor.

    I created a simple shortcode “[the_site_url]” whose purpose it merely to return the WordPress SiteURL value typically found at Settings, General page.

    While my shortcode works perfectly when viewing the published page, it fails to “render” in the Visual editor. Instead, my shortcode persists instead of being swapped with the SiteURL value.

    I thought that, by adding it as a button on the Visual editor, Tinymce would be able to evaluate my custom shortcode and produce the desired result.

    Presently, the theme resides in a development folder. Hence, SiteURL is “http://mydomain.com/dev/” but will change, once moved to production, as “http://mydomain.com” By using a shortcode, I would avoid having to use a plugin such as Blue Velvet or manual effort to update all of the embedded page and image links.

    To clarify, I am using my shortcode as such within content:
    [the_site_url]/wp-content/uploads/2013/03/yada.png

    …Which, when viewed in the browser (outside of wordpress admin mode), becomes:
    http://mydomain.com/dev//wp-content/uploads/2013/03/yada.png

    Again, this works perfectly … except for in the Visual editor.

    • http://marcheatleydesign.com Marc Heatley

      Yes, you have misunderstood the purpose of shortcodes. The idea is to allow a simple method for adding markup to the rendered page. If the shortcode expanded inside the visual editor a site user could potentially mangle the markup.