Make Shortcodes User-Friendly

Since WordPress 2.5, Shortcode has proven to be one of the most powerful features that allows lots of room for flexibility and customization. However, as anything that has the word “code” in it, shortcodes are not very user friendly. For people who are used to using WYSIWYG, shortcode usage can be confusing sometimes. This article shows you how to make shortcodes in your themes and plugins more accessible and user friendly.

Usability Problems

Take the gallery shortcode for instance. It allows users to include a WordPress gallery in a post or page. Here’s its simplest form:

[ gallery ]

But if the user wants to set more advanced options, such as the number of columns, or the thumbnail size, they’ll have to type in some attributes, which look similar to HTML attributes

[ gallery columns="4" size="medium" ]

This is not user friendly, because of the following three reasons:

  1. To customize a shortcode, most of the time you have to look at the documentation. It’s hard to memorize all the available attributes and values.
  2. Not all users are familiar with HTML syntax, as a result they might get confused about specifying attributes.
  3. It’s easy to make a typo, or specify the wrong value for an attribute.

Solution

Shortcode is, after all, code. And code is not user friendly. The less end-users have to “code”, the better.

Therefore, it’s essential that WordPress developers provide a user interface for everything that’s supposed to be customized by users. Shortcode is no exception. The best solution to deal with shortcode, is to add a button to the visual editor’s toolbar, and display a nice GUI to configure all available shortcode attributes.

What we’re going to do next, is create a small plugin that provides such an interface for the gallery shortcode.

Note: WordPress already has an UI to customize the gallery shortcode, but it’s buried deep inside the Media Manager.

So, let’s start with the bare bones of a plugin file. I’ll assume that you already know how to develop your own plugin. Otherwise, here’s your bible.

I prefer the Object Oriented approach, so here’s what I’ve got:

/*
Plugin Name: mygallery
Plugin URI: http://wphardcore.com
Description: A simple user interface for Gallery shortcode
Version: 0.1
Author: Gary Cao
Author URI: http://garyc40.com
*/

if ( ! defined( 'ABSPATH' ) )
	die( "Can't load this file directly" );

class MyGallery
{
	function __construct() {
	}

}

$mygallery = new MyGallery();

Now, there are two WordPress filters that we’ll be using to add a button to the visual editor’s toolbar.

Go back to your WordPress admin panel, activate your plugin and hook our plugin up with these filters:

function __construct() {
	add_action( 'admin_init', array( $this, 'action_admin_init' ) );
}

function action_admin_init() {
	// only hook up these filters if we're in the admin panel, and the current user has permission
	// to edit posts and pages
	if ( current_user_can( 'edit_posts' ) && current_user_can( 'edit_pages' ) ) {
		add_filter( 'mce_buttons', array( $this, 'filter_mce_button' ) );
		add_filter( 'mce_external_plugins', array( $this, 'filter_mce_plugin' ) );
	}
}

function filter_mce_button( $buttons ) {
	// add a separation before our button, here our button's id is "mygallery_button"
	array_push( $buttons, '|', 'mygallery_button' );
	return $buttons;
}

function filter_mce_plugin( $plugins ) {
	// this plugin file will work the magic of our button
	$plugins['mygallery'] = plugin_dir_url( __FILE__ ) . 'mygallery_plugin.js';
	return $plugins;
}

Here’s the hard part. Create a new javascript file in the same folder as your plugin file, and name it mygallery_plugin.js.

// closure to avoid namespace collision
(function(){
	// creates the plugin
	tinymce.create('tinymce.plugins.mygallery', {
		// creates control instances based on the control's id.
		// our button's id is "mygallery_button"
		createControl : function(id, controlManager) {
			if (id == 'mygallery_button') {
				// creates the button
				var button = controlManager.createButton('mygallery_button', {
					title : 'MyGallery Shortcode', // title of the button
					image : '../wp-includes/images/smilies/icon_mrgreen.gif',  // path to the button's image
					onclick : function() {
						// do something when the button is clicked :) 
					}
				});
				return button;
			}
			return null;
		}
	});

	// registers the plugin. DON'T MISS THIS STEP!!!
	tinymce.PluginManager.add('mygallery', tinymce.plugins.mygallery);
})()

We’re using tinyMCE’s API to register our editor plugin, and create the button. If you don’t understand what the hell happened above, just close your eyes, and forget about it for a minute (seriously), then proceed with our next step. You can always come back and dig into tinyMCE’s documentation to get a grasp of what the snippet above means.

Now go to your WordPress admin panel, edit or create a new post (or page). You’ll see our tiny little button in the toolbar, preceded by a separator:

If you click the button, nothing happens because you haven’t written any code that handles that part yet. If I cover that part in this article too, it’s going to be too long. So Download the Sourcecode and take a look for yourself. The code is abundant with documentation, but if you have any questions, shoot me a comment!

Here’s a screenshot of the final results:

mygallery.zip

51 thoughts on “Make Shortcodes User-Friendly

  1. Pingback: Top 10 WordPress Tutorials And Articles From March

  2. Pingback: 45+ Fresh Wordpress Tutorials, Techniques and Hacks - Speckyboy Design Magazine

  3. Vasili

    Can you please provede an example of adding the php code in functions.php instead of using it as a plugin, i’ve tried to do it my self, but without any luck. the icon is not showing up in the editor.

    Reply
  4. Pingback: 45+ Fresh Wordpress Tutorials « MoeMir

  5. Denys

    Hi. Good article.
    Please, can you explain how to add dropdown box in TinyMCE editor with all shortcodes that I made? If it’s not small you can send me email.
    Thank you!

    Reply
  6. John

    Thank you! Will be using this in the next version (3) of my plugin, OpenBook. I tried copying the code snippets in your article but could not turn them into a working plugin. However the downloaded code works like a charm. May thanks.

    Reply
  7. Pingback: John Miedema » OpenBook 3: New WordPress Button to Insert OpenBook Code with No Fuss

  8. Michel

    I discover today your efficient doc site… wonderful… but here the images are not visible and when clicked display an error message…NoSuchKeyThe specified key does not exist.wordpress/wp-content/uploads/2010/03/3.jpgB6011D69787F9595lprNOCJ2cm3dUxyQGfu9vo+Ul2KrwVPbQASZX9ho0fn5n1LdHBFpm5eA6twgQlZE

    Reply
  9. kucrut

    At last, a perfect example for what I’ve been looking for. Will be using this to base my theme addons.

    Thanks!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>