JDM Digital

Shortcode API

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

Get the Email

Join 1000+ other subscribers. Only 1 digest email per month. We'll never share your address. Unsubscribe anytime. It won't hurt our feelings (much).

Subscribe

Exit mobile version