Short Codes are everywhere; they are one of the main features that theme authors advertise, and they are tremendous tools for plugin developers.

Adding a short code to your plugin is quite simple, actually.

Take a look at the sample code below:

1
2
3
4
5
6
7
8
9
10
11
12
function pippin_example_shortcode( $atts, $content = null)	{
 
	extract( shortcode_atts( array(
				'message' => ''
			), $atts 
		) 
	);
	// this will display our message before the content of the shortcode
	return $message . ' ' . $content;
 
}
add_shortcode('example', 'pippin_example_shortcode');

This is just a very basic example, but it demonstrates at least 90% of everything you need to know about creating shortcodes.

The first step is to create a function that has two parameters: $atts, and $content = null. These allow us to pass options to our shortcode.

Second, we extract all of the short code parameters are store them into variables. In this case, our shortcode can accept a parameter called “message” that will be stored in a variable called $message.

Third, we return whatever is stored in $message and also the content of the shortcode.

Lastly, we use the add_shortcode() function to make the short code available for use in the editor.

It can be used like this:

[example message="Hello there!"]The message parameter will be prefixed to this content.[/example]

Our result will look like this:

Hello there! The message parameter will be prefixed to this content.

Once you know the basics of shortcodes, your possibilities are nearly endless.

  1. Brock Nunn

    Awesome and quick tutorial. Is there any simple way to add created shortcodes to a button in the wordpress editor, so that if a user clicks it, the shortcode will echo in the editor?

  2. Gordon McNevin

    Awesome, quick and easy tutorial. Creating my first plugin today and proving a lot easier than I thought. The WordPress community rocks!

    • Pippin

      Congrats on building your first plugin! When I first started, I thought it would be a lot harder than it is too.

  3. Faisal

    Still in 2014 helpful, thanks

  4. Vlad

    Everything clear. But it’s 100% functional way. While my plugin is object oriented. So I had to put add_shortcode() inside __construct() of my class. .

  5. rahul

    thanks man

Comments are closed.