Skip to Main Content

Introduced in WordPress 2.5 is the Shortcode API, a simple set of functions for creating macro codes for use in post content. For instance, the following shortcode (in the post/page content) would add a photo gallery into the page:

[shortcode_gallery]

It enables plugin developers to create special kinds of content (e.g. forms, content generators) that users can attach to certain pages by adding the corresponding shortcode into the page text.

The Shortcode API makes it easy to create shortcodes that support attributes like this:

[shortcode_gallery id=”123″ size=”medium”]

The API handles all the tricky parsing, eliminating the need for writing a custom regular expression for each shortcode. Helper functions are included for setting and fetching default attributes. The API supports both self-closing and enclosing shortcodes.

As a quick start for those in a hurry, here’s a minimal example of the PHP code required to create a shortcode:

//[foobar]
function foobar_func( $atts ){
	return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );

This will create [foobar] shortcode that returns as: foo and bar

With attributes:

// [bartag foo="foo-value"]
function bartag_func( $atts ) {
	extract( shortcode_atts( array(
		'foo' => 'something',
		'bar' => 'something else',
	), $atts ) );

	return "foo = {$foo}";
}
add_shortcode( 'bartag', 'bartag_func' );

This creates a “[bartag]” shortcode that supports two attributes: [“foo” and “bar”]. Both attributes are optional and will take on default options [foo=”something” bar=”something else”] if they are not provided. The shortcode will return as foo = {the value of the foo attribute}

Get all the details about the WordPress Shortcodes API from WordPress.org/Codex

Share the love:

Get Support

Nobody's perfect. If you need a little help, request support from the super-nerds at JDM Digital.

Any information you provide here will be kept confidential and only used for this purpose.

So we can follow-up.

The URL of the issue.

The more specific you can be, the better.

I am 100% robot

You're not a robot, are you? Sorry we have to ask.