Anatomy Of A WordPress Plugin: Adding A Shortcode

WordPressAdditional functionality can be added to posts and pages through the use of shortcodes. Up to now I have created and published six plugins of which two thirds use a shortcode to add easy-to-use additional functionality.

For example the Series Index plugin uses a [series-index] shortcode to display the series index for the posts. To use a shortcode, it first needs to be added and then the function itself which does the action specified by the shortcode is created.

A shortcode is added using the add_shortcode() function:

add_shortcode( $tag, $function );

The structure of the function call is:

  • $tag – the shortcode tag is searched for in the post or page and will be replaced with the return of the $function.
  • $function – is the hook called when the tag is found in the post or page.

In the Series Index plugin, the add_shortcode() call looks like this:

add_shortcode( 'series-index', 'azc_display_series_index' );

The tag series-index causes the plugin to look for [series-index] in a post and page and then call the function azc_display_series_index to perform the required action.

Which segues us nicely into the second part of required code which is the function which executes the shortcode. At the simplest level the function needs the following:

function shortcode_function( $atts ){
	return "shortcode output";
}

$atts are the attributes passed in via the shortcode with the return line passing back the content which will replace the shortcode.

The Series Index plugin was created to take a number of parameters. This would be done by expanding the [series-index] shortcode to include them. For example, one of the parameters is the width; if we wanted the series index to be 80% of the width of the containing div, this would be added by adding width=’80%’ to the shortcode:

[series-index width='80%']

The atributes can be extracted from the $atts using the following code:

extract(shortcode_atts(array(
		'width' => '75%'
	), $atts));

This code extracts the $width parameter from the $atts and also sets a default of 75% if the width parameter is not supplied.

After the parameters have been extracted they can be used in the function to generate any output required. The Series Index function is a bit longer and more complex than I want to post here. So instead below is a section of the shortcodes function with several parameters being passed in:

function azc_display_series_index($atts, $content = null) {
	extract(shortcode_atts(array(
		'title' => "",
		'replace' => "",
		'width' => '75%,
		'toggle' => 1,
		'heading' => ""
	), $atts));
	
	{code excised for brevity}
	
	return $output;
}

The code which uses the parameters and sets the output has been excised for purposes of brevity.

Click to show/hide the Anatomy Of A WordPress Plugin Series Index