• 赤色のリンクは、まだ日本語Codexに存在しないページ・画像です。英語版と併せてご覧ください。(詳細

このWikiはいつでも誰でも編集できます

ショートコード API

提供: WordPress Codex 日本語版
2008年5月2日 (金) 01:22時点におけるBono (トーク | 投稿記録)による版 (en:Shortcode API 2008年4月25日 (金) 16:57 MarkJaquith 版/著者: Tellyworth ほか)

(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
移動先: 案内検索

The Shortcode API

New in WordPress 2.5 is the Shortcode API, a simple set of functions for creating macro codes for use in post content. A trivial shortcode looks like this:

[gallery]

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

[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 support 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 shortcode with attributes:

// [bartag foo="bar"]
function bartag_func($atts) {
	extract(shortcode_atts(array(
		'foo' => 'no foo',
		'baz' => 'default baz',
	), $atts));

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

This creates a "[bartag]" shortcode that supports two attributes: [bartag foo="something" bar="something else"]. Both attributes are optional and will take on default options if they are not provided.

Overview

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).

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 handler function name.

A shortcode handler function should accept one or two attributes: $atts, an array of attributes, and $content, the enclosed content (if the shortcode is used in its enclosing form). For example:

function my_shortcode_handler($atts, $content=null) {
}

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

add_shortcode('my-shortcode', 'my_shortcode_handler');

When the_content is displayed, the shortcode API will parse any registered shortcodes such as "[my-shortcode]", separate and parse the attributes and content, if any, and pass them the corresponding shorcode handler function. Any string returned by the shortcode handler will be inserted into the post body in place of the shortcode itself.

Shortcode attributes such as these:

[my-shortcode foo="bar" baz="bing"]

Will be converted into an associative array like this, to be passed to the handler function as its $atts parameter:

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

The array keys are the attribute names, array values are the corresponding attribute values.

Attributes

The raw $atts array may include any arbitrary attributes that are specified by the user. 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. And there is no 'bar' item in the defaults array, so it is not included in the result.

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

function my_shortcode_handler( $atts, $content = null ) {
   extract( 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 (using extract()) store the results in local variables named for the attribute keys - $attr_1, $attr_2 and so on. In other words, the array of defaults approximates a list of local variable declarations. (extract() is safe to use in this context without special flags to handle collisions because shortcode_atts() will strip out any keys not included in the defaults array).

Output

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.

Enclosing vs self-closing shortcodes

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

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:

[caption]My Caption[/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:

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

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]Caption: [my-shortcode][/caption]

This would produce:

<span class="caption">Caption: [my-shortcode]</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 "[my-shortcode]" macro in the enclosed content is parsed, and its output enclosed by the caption span:

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

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 ) {
   extract( shortcode_atts( array(
      'class' => 'caption',
      ), $atts ) );
 
   return '<span class="' . attribtue_escape($caption) . '">' . $content . '</span>';
}
[caption class="headline"]My Caption[/caption]
<span class="headline">My Caption</span>

Other features in brief

  • The parser supports xhtml-style closing shortcodes like "[my-shortcode /]", but this is optional.
  • Attribute names are always converted to lowercase before they are passed into the handler function. Values are untouched. [my-shortcode FOO="BAR"] produces $atts = array( 'foo' => 'BAR' ).
  • Shortcode macros may use single or double quotes for attribute values, or omit them entirely if the attribute value does not contain spaces. [my-shortcode foo='123' bar=456] is equivalent to [my-shortcode foo="123" bar="456"].
  • For backwards compatibility with older ad-hoc shortcodes, attribute names may be omitted. If an attribute has no name it will be given a positional numeric key in the $atts array. For example, [my-shortcode 123] will produce $atts = array( 0 => 123 ). Positional attributes may be mixed with named ones, and quotes may be used if the values contain spaces or other significant characters.

Function reference

The following Shortcode API functions are available:

function add_shortcode($tag, $func)

Registers a new shortcode handler function. $tag is the shortcode string as written by the user (without braces), such as "my-shortcode". $func is the handler function name.

Only one handler function may exist for a given shortcode. Calling add_shortcode() again with the same $tag name will overwrite the previous handler.

function remove_shortcode($tag)

Deregisters an existing shortcode. $tag is the shortcode name as used in add_shortcode().

function remove_all_shortcodes()

Deregisters all shortcodes.

function shortcode_atts($pairs, $atts)

Process a raw array of attributes $atts against the set of defaults specified in $pairs. Returns an array. The result will contain every key from $pairs, merged with values from $atts. Any keys in $atts that do not exist in $pairs are ignored.

function do_shortcode($content)

Parse any known shortcode macros in the $content string. Returns a string containing the original content with shortcode macros replaced by their handler functions' output.

do_shortcode() is registered as a default filter on 'the_content' with a priority of 11.

Limitations

The shortcode parser correctly deals with nested shortcode macros, provided their handler functions support it by recursively calling do_shortcode():

[tag-a]
   [tab-b]
      [tag-c]
   [/tag-b]
[/tag-a]

However the parser will fail if a shortcode macro is used to enclose another macro of the same name:

[tag-a]
   [tag-a]
   [/tag-a]
[/tag-a]

This is a limitation of the context-free regexp parser used by do_shortcode() - it is very fast but does not count levels of nesting, so it can't match each opening tag with its correct closing tag in these cases.

External Resources

Shortcode summary by Aaron D. Campbell - Explains shortcodes and gives examples including how to incorporate shortcodes into a meta box for sending them to the editor using js.