Creating Custom Shortcode Plugins

Posted Aug 2, 2013

You've probably used shortcodes before, but you might not know that creating a shortcode is pretty easy. You might want to create your own shortcode if you'll be handing off a site to a client who doesn't know HTML, if you want to make something you're constantly using in posts easier, or if theres something in your posts that might need to have its HTML changed in the future.

If you've ever created your own theme or even a simple plugin, you should be able to create your own shortcodes. If you've never written a plugin before and would like to create your shortcode inside a plugin, check out our tutorial on writing your first plugin. It's also possible to create a shortcode within your theme's functions.php file.

Once you have your plugin started or have functions.php open, there's only two things we need to do to create our shortcode. The first thing we'll need is a function that returns the HTML we want to display. In this example we'll be placing an ad in our posts, so let's create a simple function to return the HTML:

function my_ad_shortcode() {
    return '<div class="ad"><!-- This is our ad --></div>';
}

You can replace the HTML with whatever you need to display, just be sure to use return and not echo. Now that we have a function to return our shortcode's HTML, all we need to do is tell WordPress about it.

add_shortcode( 'my_ad', 'my_ad_shortcode' );

This creates the [myad] shortcode and tell WordPress to execute the myad_shortcode() function in its place. One of the great advantages of using a shortcode in this example is that we can control the HTML for all of our ads in one place instead of painfully going through all our posts and updating the code.

Here's our finished product:

<?php

/*
Plugin Name: My Ad Shortcode
Plugin URI: http://refactored.co/blog/creating-custom-shortcode-plugins
Description: A simple shortcode plugin
Author: Refactored Co.
Author URI: http://refactored.co
Version: 0.1
License: GPL2
*/

// Our shortcode function
function my_ad_shortcode() {
    return '<div class="ad"><!-- This is our ad --></div>';
}

// Tell WordPress about it
add_shortcode( 'my_ad', 'my_ad_shortcode' );

?>

There's a lot more you can do with shortcodes, so be sure to check out the Shortcode API docs to learn more.