A fresh mix of code snippets and tutorials

WordPress Create Shortcode

Ultra-quick guide to help you create a WordPress Shortcode. Aimed at experienced WordPress users who need a basic example of how to create shortcodes.

Create a simple shortcode

The first thing I would recommend is try to create a simple shortcode. Then once you see how it works, continue with a more advanced example. Here is an example of a basic WordPress Shortcode:

function simple_shortcode_example() {  
	return '<p>This is a simple example of a WordPress shortcode.</p>';  
add_shortcode('simple_example', 'simple_shortcode_example');

Here we have a basic PHP function named simple_shortcode_example() that returns a simple paragraph and some text. The function is hooked into add_shortcode() to make it an actual WordPress Shortcode. The first parameter is the shortcode name and the second parameter is the function name.

After adding this code snippet to your theme’s functions.php file, you can call it by adding the following shortcode to any Post or Page:


This will output the line specified in the simple_shortcode_example() function:

<p>This is a simple example of a WordPress shortcode.</p>

Now that you’ve seen how a basic shortcode works, let’s look at a (slightly) more advanced example.

Slightly more advanced example

The key to writing more advanced shortcodes is to understand how attributes are used. Consider the following example, which also would be added via functions.php:

function advanced_shortcode_example($atts, $content = null) {
		'href' => 'http://example.com/'
	), $atts));
	return '<a href="'. $href .'">'. $content .'</a>';
add_shortcode('url', 'advanced_shortcode_example');

The key things to notice here are:

  • Two variables are passed to the function, $atts and $content
  • $atts is an array that is extracted using extract(shortcode_atts())
  • The array defines the default value of the $href variable
  • The default href value is overridden by the href contained in the $atts array
  • $content is defined in the shortcode itself and used for the link text

As with the simple example, here we make the advanced_shortcode_example() function an actual WordPress Shortcode by hooking into add_shortcode().

Once the shortcode function is included, the shortcode can be called like so:

[url href="https://wp-mix.com/"]Awesome code snippets[/url]

When included on any Post or Page, that shortcode will display a link that says, “Awesome code snippets”, and points to https://wp-mix.com/ :)

For more thorough/detailed information on WordPress Shortcodes, check out the WP Codex (see reference link below).


Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress