wordpress shortcode

The 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:

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:

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:

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 ) {
    $a = shortcode_atts( array(
        'foo' => 'something',
        'bar' => 'something else',
    ), $atts );

    return "foo = {$a['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}.


Shortcodes are written by providing a handler function. Shortcode handlers are broadly similar to WordPress filters: they accept parameters (attributes) and return a result (the shortcode output).

Shortcode names should be all lowercase and use all letters, but numbers and underscores should work fine too. Be wary of using hyphens (dashes), you’ll be better off not using them.

The add_shortcode function is used to register a shortcode handler. It takes two parameters: the shortcode name (the string used in a post body), and the callback function name.

Three parameters are passed to the shortcode callback function. You can choose to use any number of them including none of them.

  • $atts – an associative array of attributes, or an empty string if no attributes are given
  • $content – the enclosed content (if the shortcode is used in its enclosing form)
  • $tag – the shortcode tag, useful for shared callback functions

The API call to register the shortcode handler would look something like this:

add_shortcode( 'myshortcode', 'my_shortcode_handler' );

When the_content is displayed, the shortcode API will parse any registered shortcodes such as « [myshortcode] », separate and parse the attributes and content, if any, and pass them the corresponding shortcode handler function. Any string returned (not echoed) by the shortcode handler will be inserted into the post body in place of the shortcode itself.

Shortcode attributes are entered like this:

[myshortcode foo="bar" bar="bing"]

These attributes will be converted into an associative array like the following, passed to the handler function as its $atts parameter:

array( 'foo' => 'bar', 'bar' => 'bing' )

The array keys are the attribute names; array values are the corresponding attribute values. In addition, the zeroeth entry ($atts[0]) will hold the string that matched the shortcode regex, but ONLY IF that is different from the callback name. See the discussion of attributes, below.


The raw $atts array may include any arbitrary attributes that are specified by the user. (In addition, the zeroeth entry of the array may contain the string that was recognized by the regex; see the note below.)

In order to help set default values for missing attributes, and eliminate any attributes that are not recognized by your shortcode, the API provides a shortcode_atts() function.

shortcode_atts() resembles the wp_parse_args function, but has some important differences. Its parameters are:

shortcode_atts( $defaults_array, $atts );

Both parameters are required. $defaults_array is an associative array that specifies the recognized attribute names and their default values. $atts is the raw attributes array as passed into your shortcode handler. shortcode_atts() will return a normalized array containing all of the keys from the $defaults_array, filled in with values from the $atts array if present. For example:

$a = shortcode_atts( array(
    'title' => 'My Title',
    'foo' => 123,
), $atts );

If $atts were to contain array( 'foo' => 456, 'bar' => 'something' ), the resulting $a would be array( 'title' => 'My Title', 'foo' => 456 ). The value of $atts['foo'] overrides the default of 123. $atts['title'] is not set, so the default ‘My Title’ is used. There is no ‘bar’ item in the defaults array, so it is not included in the result.

Attribute names are always converted to lowercase before they are passed into the handler function. Values are untouched.[myshortcode FOO="BAR"] produces $atts = array( 'foo' => 'BAR' ).

A suggested code idiom for declaring defaults and parsing attributes in a shortcode handler is as follows:

function my_shortcode_handler( $atts, $content = null ) {
    $a = shortcode_atts( array(
        'attr_1' => 'attribute 1 default',
        'attr_2' => 'attribute 2 default',
        // ...etc
    ), $atts );

This will parse the attributes, set default values, eliminate any unsupported attributes, and store the results in a local array variable named $a with the attributes as keys – $a['attr_1'], $a['attr_2'], and so on. In other words, the array of defaults approximates a list of local variable declarations.

IMPORTANT TIP – Don’t use camelCase or UPPER-CASE for your $atts attribute names
$atts values are lower-cased during shortcode_atts( array( 'attr_1' => 'attr_1 default', // ...etc ), $atts ) processing, so you might want to just use lower-case.

NOTE on confusing regex/callback name reference
The zeroeth entry of the attributes array ($atts[0]) will contain the string that matched the shortcode regex, but ONLY if that differs from the callback name, which otherwise appears as the third argument to the callback function.
(Appears to always appear as third argument as of 2.9.2.)
 add_shortcode('foo','foo'); // two shortcodes referencing the same callback
    produces this behavior:
 [foo a='b'] ==> callback to: foo(array('a'=>'b'),NULL,"foo");
 [bar a='c'] ==> callback to: foo(array(0 => 'bar', 'a'=>'c'),NULL,"");

This is confusing and perhaps reflects an underlying bug, but an overloaded callback routine can correctly determine what shortcode was used to call it, by checking BOTH the third argument to the callback and the zeroeth attribute. (It is NOT an error to have two shortcodes reference the same callback routine, which allows for common code.)


The return value of a shortcode handler function is inserted into the post content output in place of the shortcode macro. Remember to use return and not echo – anything that is echoed will be output to the browser, but it won’t appear in the correct place on the page.

Shortcodes are parsed after wpautop and wptexturize post formatting has been applied (but see the note below about 2.5.0 and 2.5.1 differences). This means that your shortcode output HTML won’t automatically have curly quotes applied, p and br tags added, and so on. If you do want your shortcode output to be formatted, you should call wpautop() or wptexturize() directly when you return the output from your shortcode handler.

wpautop recognizes shortcode syntax and will attempt not to wrap p or br tags around shortcodes that stand alone on a line by themselves. Shortcodes intended for use in this manner should ensure that the output is wrapped in an appropriate block tag such as <p> or <div>.

Note: in WordPress 2.5.0, shortcodes were parsed before post formatting was applied, so the shortcode output HTML was sometimes wrapped in p or br tags. This was incorrect behaviour that has been fixed in 2.5.1.

If the shortcode produces a lot of HTML then ob_start can be used to capture output and convert it to a string as follows:-

function myShortCode() {
	?> <HTML> <here> ... <?PHP
	return ob_get_clean();

Enclosing vs self-closing shortcodes

The examples above show self-closing shortcode macros such as [myshortcode]. The API also supports enclosing shortcodes such as [myshortcode]content[/myshortcode].

If a shortcode macro is used to enclose content, its handler function will receive a second parameter containing that content. Users might write shortcodes in either form, so it is necessary to allow for either case by providing a default value for the second parameter to your handler function:

function my_shortcode_handler( $atts, $content = null )

is_null( $content ) can be used to distinguish between the self-closing and enclosing cases.

When content is enclosed, the complete shortcode macro including its content will be replaced with the function output. It is the responsibility of the handler function to provide any necessary escaping or encoding of the raw content string, and include it in the output.

Here’s a trivial example of an enclosing shortcode:

function caption_shortcode( $atts, $content = null ) {
	return '<span class="caption">' . $content . '</span>';
add_shortcode( 'caption', 'caption_shortcode' );

When used like this:

My Caption

The output would be:

<span class="caption">My Caption</span>

Since $content is included in the return value without any escaping or encoding, the user can include raw HTML:

<a href="http://example.com/">My Caption</a>

Which would produce:

<span class="caption"><a href="http://example.com/">My Caption</a></span>

This may or may not be intended behaviour – if the shortcode should not permit raw HTML in its output, it should use an escaping or filtering function to deal with it before returning the result.

The shortcode parser uses a single pass on the post content. This means that if the $content parameter of a shortcode handler contains another shortcode, it won’t be parsed:

Caption: [myshortcode]

This would produce:

<span class="caption">Caption: [myshortcode]</span>

If the enclosing shortcode is intended to permit other shortcodes in its output, the handler function can call do_shortcode() recursively:

function caption_shortcode( $atts, $content = null ) {
   return '<span class="caption">' . do_shortcode($content) . '</span>';

In the previous example, this would ensure the « [myshortcode] » macro in the enclosed content is parsed, and its output enclosed by the caption span:

<span class="caption">Caption: The result of myshortcode's handler function</span>

The parser does not handle mixing of enclosing and non-enclosing forms of the same shortcode as you would want it to. For example, if you have:

[myshortcode example='non-enclosing' /] non-enclosed content [myshortcode] enclosed content [/myshortcode]

Instead of being treated as two shortcodes separated by the text  » non-enclosed content « , the parser treats this as a single shortcode enclosing  » non-enclosed content [myshortcode] enclosed content ».

Enclosing shortcodes support attributes in the same way as self-closing shortcodes. Here’s an example of the caption_shortcode() improved to support a ‘class’ attribute:

function caption_shortcode( $atts, $content = null ) {
	$a = shortcode_atts( array(
		'class' => 'caption',
	), $atts );

	return '<span class="' . esc_attr($a['class']) . '">' . $content . '</span>';
My Caption
<span class="headline">My Caption</span>


Function Reference/shortcode atts


Combines user shortcode attributes with known attributes and fills in defaults when needed. The result will contain every key from the known attributes, merged with values from shortcode attributes.


<?php shortcode_atts( $pairs , $atts, $shortcode ); ?>


(array) (required) Entire list of supported attributes and their defaults

Default: None
(array) (required) User defined attributes in shortcode tag

Default: None
(string) (optional) Shortcode name to be used by the shortcode_atts_{$shortcode} filter. Even if this parameter is optional, do not(!) avoid it. Else it will be impossible for plugins to target this shortcode for pre-processing.

Default: None

Return Values

Combined and filtered attribute list.


function bartag_func( $atts ) {
	$atts = shortcode_atts(
			'foo' => 'no foo',
			'bar' => 'default bar',
		), $atts, 'bartag' );

	return 'bartag: ' . $atts['foo'] . ' ' . $atts['bar'];
add_shortcode( 'bartag', 'bartag_func' );

[bartag foo= »koala » bar= »bears »] outputs the following:
bartag: koala bears



Laisser un commentaire

Entrer les renseignements ci-dessous ou cliquer sur une icône pour ouvrir une session :

Logo WordPress.com

Vous commentez à l’aide de votre compte WordPress.com. Déconnexion /  Changer )

Photo Google

Vous commentez à l’aide de votre compte Google. Déconnexion /  Changer )

Image Twitter

Vous commentez à l’aide de votre compte Twitter. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l’aide de votre compte Facebook. Déconnexion /  Changer )

Connexion à %s