WordPress:Shortcode API

来自站长百科
跳转至: 导航、​ 搜索

短码 API[ ]

Shortcode API是WordPress2.5版本的新功能,是一组简单的函数,用来创建文章内容中可以使用的宏代码。一个小的shortcode看起来像: [gallery]

Shortcode API使得创建像支持下面的属性的shortcodes变得非常简单: [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.

API处理了所有形式的解析工作,不需要为每个简码编写正规的的自定义的表达式。API包括Helper函数用来设置和获取默认属性。API支持是自动关闭和被动关闭的简码。

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

快速地开始认识这些,下面有一个的例子,用最少的PHP代码创建带有属性的简码:

// [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');

// [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. 例子中创建的简码"[bartag]",支持两个属性:[bartag foo="something" bar="something else"]。这两个属性都是可选的,如果没有提供,它们就会采纳默认值。


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

简码是用来提供处理函数的。简码处理器在很大程度上类似于WordPress过滤器:它们都接受参数(属性)并返回结果(简码输出)。 函数add_shortcode()用于注册简码处理器。它有两个参数:简码名(用于文章本身的字符串)和处理器函数名。

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.

函数add_shortcode()用于注册简码处理器。它有两个参数:简码名(用于文章本身的字符串)和处理器函数名。

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:

简码处理器函数应该接受一到两个属性:$atts(属性的数组)和$content,其中的内容(如果简码用于包含其中的表单)。例如: function my_shortcode_handler($atts, $content=null) {

}

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

The API call to register the shortcode handler would look something like this: 用于注册简码处理器的API调用,形式如下:

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

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. 当the_content显示的时候,简码API就会解析所有注册的简码,比如"[my-shortcode]",如果有属性和内容,就会把它们分离并解析出来,然后传递给相应的简码处理器函数。任何由处理器返回的字符串都会被插入到文章本身,替换掉简码的位置。 Shortcode attributes such as these:

简码属性如下:

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

[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: 它们会被转化为关联数组(如下),作为$atts参数传递给处理器函数:

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

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.

raw $atts数组可能包含用户规定的任何任意的属性。为了为丢失的属性设置默认值并且删除不是你的简码组织的属性,API提供了shortcode_atts()函数。

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

shortcode_atts()类似与wp_parse_args()函数,但是两者之间有一些关键的不同点。shortcode_atts()的参数是:

shortcode_atts( $defaults_array, $atts );

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:

两个参数都需要。$defaults_array是一个联合的数组,明确规定了组织的属性名称和默认值。 $atts是raw 属性数组,传递到你的简码处理器。shortcode_atts()会返回规格化的数组,包含所有来自$defaults_array的键,如果有来自$atts array的参数值,就会被填上这个值。例如:

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

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

如果$atts将要包含数组( 'foo' => 456, 'bar' => 'something' ),结果$a会是数组( 'title' => 'My Title', 'foo' => 456 )。$atts['foo']的值取消了默认值123。$atts['title']没有设置,因此使用了默认的'我的标题'。而且默认数组中没有'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 ) {
   extract( shortcode_atts( array(
      'attr_1' => 'attribute 1 default',
      'attr_2' => 'attribute 2 default',
      // ...etc
      ), $atts ) );
}


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

这会解析属性,设置默认值,删除任何无支持的属性,并且(使用extract())将结果储存在本地变数中,命名为属性键-$attr_1, $attr_2 等等。换句话说,默认的数组接近与本地变数声明的一个列表。(在这个文本中使用extract(),非常安全,没有特别的标记处理冲突,因为shortcode_atts()会剥去任何默认数组中不包含的键)。

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.

短码处理器函数的返回值插入了文章内容中,取代了短码宏。记住使用返回而不是echo-任何经过echo的内容都会输出到浏览器中,但是不会出现在网页上的适当位置上。

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和 wptexturize文章格式之后,短码就得到了解析(但是看看下面的记录,关于2.5.0和2.5.1之间的不同点)。这意味着,你的短码输出的HTML不会自动地应用curly quotes,添加p和br标签,等等。如果你真的想要你的短码输出为一定的格式,当你从短码处理器返回输出的时候,你应该直接地调用wpautop() 或者 wptexturize()。

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

Wpautop组织了短码语法,而且试着不在独立排在一行的短码周围添加p或者br标签。将要以这样方式使用的短码应该确保输出包裹在适当的block标签中,例如<p> 或者 <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.

注:在WordPress2.5.0版本中,短码解析后,才会使用文章格式,因此短码输出HTML有时候包裹在p或者br标签中。这个操作是错误的,而且在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].

上述的例子显示了自动关闭的短码宏,例如[my-shortcode]。API也支持被动关闭的短码,如[my-shortcode]内容[/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 )

function my_shortcode_handler( $atts, $content = null )

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

is_null($content)可以用来区分自动关闭和被动关闭的情况。

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.

包含了内容之后,完全的短码宏包含内容会被函数输出取代。处理乐趣函数有义务提供必须的escaping或者对raw内容字符串的编码,并将其包含在输出中。

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');

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]

[caption]My Caption[/caption]

The output would be: 输出是:

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

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

因为$content包含在返回值内,没有任何escaping或者编码,用户可以包含raw HTML:

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

[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>

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

这可能是或者不是有意的操作-如果短码输出不允许raw HTML,那么应该使用escaping或者过滤函数,处理raw HTML,再输出结果。

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:

短码分析器对于文章内容使用单一传递。这指的是,如果短码处理器的$content参数包含另一个短码,就得不到解析:

[caption]Caption: [my-shortcode][/caption]

[caption]Caption: [my-shortcode][/caption]

This would produce: 这会产出:

<span class="caption">Caption: [my-shortcode]</span>

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

如果被动关闭的短码试图在输出内允许另一个短码,处理器函数可以递归地调用do_shortcode():

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

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:

在上一个例子中,这会确保附加的内容中的"[my-shortcode]"宏得到解析,而且其输出会由caption span包围:

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

被迫关闭的短码和自动关闭的短码支持属性的方式是相同的。下面是caption_shortcode()改进支持'class'属性:

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>

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.
  • 分析器支持xhtml-style closing shortcodes像"[my-shortcode /]",但是这是不可选的。
  • 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' ).
  • 属性名通常转化为小写的,再传递到处理器函数中。参数值未改。[my-shortcode FOO="BAR"]产出$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"].
  • 短码宏可能使用单引号或者双引号,引用属性值,如果属性值不包含空格,短码宏就会完全忽略属性值。[my-shortcode foo='123' bar=456]和[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.
  • 与旧的ad-hoc短码的向后兼容,属性名可能会被省略。如果属性没有名称,会得到$atts数组中的表示位置的数值。例如[my-shortcode 123]会输出$atts = array( 0 => 123 )。位置属性可能与命名属性混合,如果参数值包含空格或者其它重要的字符,可能会使用到引号。
  • 短码API拥有test cases。Tests—包含许多错误的例子和不正常的语法—可以在http://svn.automattic.com/wordpress-tests/wp-testcase/test_shortcode.php找到。

Function reference[ ]

函数reference[ ]

The following Shortcode API functions are available: 你可以得到下面的短码API函数:

function add_shortcode($tag, $func)

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.

注册一个新的短码处理器函数。$tag是用户写的短码字符串(没有括号),例如"my-shortcode"。$func是处理器函数名。

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

给出的短码可能只存在一个处理器函数。用相同的$tag名称再次调用add_shortcode()会覆盖先前的处理器。

function remove_shortcode($tag)

function remove_shortcode($tag)

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

撤销当前存在的一个短码。$tag是用在add_shortcode()中的短码名。

function remove_all_shortcodes()

function remove_all_shortcodes()

Deregisters all shortcodes. 撤销所有的短码。

function shortcode_atts($pairs, $atts)

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.

处理a raw array of attributes $atts与$pairs规定的一套默认设置相对。返回一个数组。默认会包含来自$pairs中的每个键,并且将其与$atts中的值相结合。$atts中的任何值,不存在在$pairs中,都会被忽视。

function do_shortcode($content)

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.

解析$content字符串中任何熟知的短码宏。返回字符串,包含原始内容,将短码宏替换为处理器函数输出结果。

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

do_shortcode() i在 'the_content' 上注册为默认过滤器,优先11。

Limitations[ ]

限制[ ]

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

短码解析器正确地处理了嵌套的短码宏,前提是通过递归地调用do_shortcode(),短码解析器的处理器函数会支持:

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

[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]

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

这是do_shortcode()使用的context-free regexp解析器的局限性-速度非常快,但是不能计算出嵌套的级别,因此不能用这些例子中正确的关闭标签匹配每个打开的标签。

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. Aaron D. Campbell的短码总结-解释了短码,并且举出了例子,关于怎样在meta box中包含短码,用js将短码发送到编辑器。