Custom Shortcodes for WordPress

Share this article

WordPress Custom Shortcodes

What Are Shortcodes?

Shortcodes are a convenient method that WordPress implements which provides a way to generate dynamic and often complex functionality from very little input.

While developers often create functionality to provide additional features for a website; they are executed by calling PHP code. Users however, are often not developers, and as such having them interact directly with PHP is not recommended. A solution to this is for developers to create custom shortcodes.

Shortcodes provide a level of dynamic content for the user, allowing them to create power features on their website by using pseudo-code that act similar to macros. The shortcode when called will take its arguments (if any) and then run through a function which defines what custom functionality will occur.

For example, you may have a basic shortcode that is wrapped around your links to create a pretty button: [pretty_button] Read More! [/pretty_button]

Who Creates Shortcodes?

Shortcodes have to be registered on your website in order for them to be used. There are several ways in which shortcodes can be added to your website, here are a few common methods.

Added by WordPress Itself

WordPress actually comes with a series of shortcodes already defined. These shortcodes are generally used for galleries, captions, audio and video elements and mostly related to the media side of WordPress.

For example, you may want to display an inline video player on your page. By using the video shortcode as follows [video src="video-source.mp4"] you can define that a video player will be outputted on your page / post.

There are several shortcodes that are documented on the WordPress codex page

Inbuilt into a Theme

A lot of theme developers will provide a series of shortcodes that you can use to add a lot of extra functionality to your website. These shortcodes may create interactive elements, display content in visually stunning ways or be very informational.

When purchasing themes or using popular free themes, the developer will often provide a page on their website that outlines their included shortcodes (along with how to use them and examples). In addition, the theme even may include a shortcode button on the content editor (which allows a simple way to insert your shortcode)

However, a theme may also have no extra shortcodes at all.

Comes with a Plugin

Most plugins that offer some sort of content (such as forms, sliders, interactive elements) will come with a shortcode that you either configure on a case by case basis (you add the options inside the shortcode on the desired page) or is configured globally (inside a plugins theme menu for example).

These plugin shortcodes often are well documented on the developers website or the plugin repository for WordPress, giving you an instant idea of what exactly you can do with your shortcode.

For example, you may want to show your product cart on a WooCommerce powered website, you could do this by using their cart shortcode [woocommerce_cart]. These shortcodes are outlined on their shortcode documented page.

Types of Shortcodes

Now that you know what shortcodes are and how they can be added to your website, we can discuss the two different types of shortcodes and how they differ.

Non Enclosed Shortcodes

Non Enclosed shortcodes are shortcodes that do not contain or wrap other content. These shortcodes exist as a single self closed unit.

For example, say you wanted to display a gallery in your post, you would use the [gallery] shortcode. This shortcode would execute and display a gallery that would be outputted on the page.

See how the shortcode exists as a single unit, this is a non enclosed shortcode. These types of shortcodes are similar to self closing HTML elements (such as the <br/> tag)

Enclosed Shortcodes

Enclosed shortcodes are shortcodes that contain other elements or content. These shortcodes look similar to the non enclosed variety of shortcodes, but they will have a beginning and end element.

For example, say that you wanted some text on your page to stand out. You could define a shortcode that takes its wrapped content and applies a set style (such as making it bolder or bigger).

A shortcode defined as [big_and_bold] when applied to content could look similar to this [big_and_bold] This is big and bold [/big_and_bold]

Notice how we have a start tag and an end tag? All of the content between there will be passed into the shortcode and processed in some way.

Overall, when you are dealing with shortcodes you will deal with one of these two types.

Creating Your Own Shortcodes

Creating shortcodes for use in WordPress is fairly straightforward. It involves a callback function that defines what the shortcode will do and the use of the add_shortcode($name,$callback_function) function that registers the shortcode for use.

To register your own shortcodes you will need to place them inside your functions.php file inside your child theme (or if you have another file that has access to PHP you can use this also).

Remember to never edit a parent theme directly!

Defining the Shortcodes Callback Function

The functionality that a shortcode performs is defined inside the callback function.

The callback function returns a value and that value is what is displayed to the end user when generating their page/post. This returned value might just be a value wrapped in a container for styling, or it may be as complex as outputting a dynamic form element or slider.

The structure of a callback function in its simplest sense is just a function that returns a value:

//defines the callback function used for our shortcode (does nothing)
function my_shortcode_callback_function(){
	return; 
}

Shortcodes Arguments in the Callback Function

While shortcodes just need a callback function to operate; shortcodes can take arguments (options) that can be used to dynamically change how the shortcode functions.

There are three main arguments that can be passed into the function that displays the shortcode. These variables are all optional but are frequently used. These variables are $atts, $content and $name; they are called sequentially into the call back functions as such:

//defines the callback function used for our shortcode (does nothing). Takes in three arguments
function my_shortcode_callback_function($atts, $content, $name){
	return; 
}

$atts (the options)

The $attsvariable is an associative array of options or settings that you would like your shortcode to have access to.

Shortcodes will often provide the user with a series of settings which they can pass into the shortcode to give them the ability to alter the output.

For example, consider the inbuilt audio shortcode .

This shortcode (since WordPress 3.6) gives the user the ability to embed a HTML5 audio player into the page.

By default you can use the shortcode just as it is. However you can also customise its options by passing in arguments such as the following . This allows you to set the audio to pre-load as soon as the page loads, along with automatically triggering the audio (and once the audio is finished it will loop). These settings along with others can be customised by passing in values.

Let’s go through a basic example where we want a shortcode that takes in an option and outputs content conditionally based on its selection:

//based on the passed in profession, return a statement 
//Shortcodes functions and information
function display_my_profession_callback($atts,$content,$tag){
	
	//collect values, combining passed in values and defaults
	$values = shortcode_atts(array(
		'profession_type' => 'other'
	),$atts);  
	
	
	//based on input determine what to return
	$output = '';
	if($values['profession_type'] == 'developer'){
		$output = 'You are an amazing developer!';
	}
	else if($values['profession_type'] == 'designer'){
		$output = 'You are an epic designer!';
	}
	else if($values['profession_type'] == 'other'){
		$output = 'You are a great person';
	}
	else{
		$output = 'I am not sure what you are'; 
	}
	
	return $output;
	
}
add_shortcode('display_profession','display_my_profession_callback');

The first thing you will see is that we called a function named shortcode_atts(). This function is used to return an associative array of values for you to use. This function takes in your $atts variable and also defines nice default options for you to use (this takes the hassle out of merging arrays and controlling data yourself).

In our example $values will have access to one value called profession_type, however, if we defined more default values we could also access them.

The default value for profession_type is other. This value can be over-ridden in the shortcode itself by simply supplying a value, for example [display_profession type='designer']

Once we determine the value for profession_type we format a string and return it for display to the end user.

$content (the content)

The $content variable is used for enclosed shortcodes and this value represents any content that exists between the opening and closing tag of the shortcode.

For example, if you have a shortcode that makes selected text really small such as [small_text] This text will be small [/small_text]. The value of $content will be ‘This text will be small’. This variable gives the shortcode access to the content and it is how shortcodes directly apply styles and functionality to the selected areas.

Let’s look at a coding example to illustrate this.

We can create a shortcode that takes in its wrapped around content and formats it via a span tag:

//take the wrapped around content of the shortcode and style it
function wrap_content_shortcode_callback($atts, $content, $tag){
	$output = '<span style="font-size: 120%;">' . $content . '</span>';
	return $output;
}
add_shortcode('wrap_shortcode','wrap_content_shortcode_callback');

The returned content will be styled differently, wrapped around by a span.

On a related note, if you are creating shortcodes that use the $content variable, you can also use the do_shortcode($content) function. This function will take the content and run any other shortcodes inside of it. If you don’t include this and you wrap a shortcode inside another shortcode, the inner most shortcode will simply display text instead of being transformed.

$tag (the shortcode name)

The $tag variable contains the name of the shortcode itself. This is often used for shortcodes that share the same callback function.

When you define multiple shortcodes and use the same function to handle all of them you can use the $tag variable to distinguish what shortcode is being called.

Let’s look at a practical example where a single callback function is used for two shortcodes:

//this callback function performs many actions depending on which shortcode ($tag) calls it
function display_my_shortcode($atts, $content, $tag){
	
	//if called from the 'my_primary_shortcode' shortcode
	if($tag == 'my_primary_shortcode'){
		return 'This is the primary shortcode'; 
	}
	//if called from the 'my_secondary_shortcode' shortcode
	else if($tag == 'my_secondary_shortcode'){
		return 'This is the secondary shortcode'; 
	}
	//default 
	else{
		return 'This is something else'; 
	}
}
add_shortcode('my_primary_shortcode','display_my_shortcode');
add_shortcode('my_secondary_shortcode','display_my_shortcode');

Depending on what shortcode you call (either [my_primary_shortcode] or [my_secondary_shortcode] the content will differ.

Registering the shortcode with the add_shortcode() function

To register a shortcode all you need to do is call the add_shortcode($name, $callback_name) function.

This function takes two parameters; the name of the shortcode (the name that will be used in the editor) and the name of the callback function that returns the output (that does the actual processing)

As an example, look at the following:

//callback function for the 'clear_content' shortcode
function clear_content_callback_function($atts, $content, $tag){
	return '<div style="clear: both; float: left">' . $content '</div>';
}
//add the new 'clear_content' shortcode
add_shortcode('clear_content','clear_content_callback_function');

The shortcode name itself should be all lowercase and with only digits and underscores.

There have been long standing issues with the use of hyphens in shortcodes so I would simply define your shortcodes without them, but you are free to do so if you are feeling adventurous.

In Conclusion

Now that you have a thorough understanding of how shortcodes work and how they can be used to provide non developers with extensible options, you can create your own shortcodes and really extend your upcoming WordPress websites.

Simon CodringtonSimon Codrington
View Author

Full stack developer and overall web enthusiast. I love everything to do with web / design and my passion revolves around creating awesome websites. Focusing primarily on WordPress, I create themes, plugins and bespoke solutions.

ChrisBcustom shortcodesshortcodeshortcodesWordPress
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week