WordPress 从 2.5 的版本开始,增加了一个 shortcode (短代码) API ,类似于 BBS 上的 BBCode , shortcode 也可以很方便的为文章或页面增加功能,并且 shortcode 的比起 BBCode 更加灵活和强大。下面 Kayo 为大家介绍一下 shortcode 。
一.shortcode 简介
shortcode 可以让开发者通过以函数的形式创建宏内容来生成内容,或许这个概念看上去有点模糊,但实际上它是一个很简单而实用的功能,只要会编写基本的 PHP 函数,即可使用 shortcode ,下文会以实际的例子来说明 shortcode 的使用方法。
二.shortcode 形式
shortcode 支持封闭标签和自闭(自动封闭)标签,并且支持在标签内使用参数,至于 shortcode 具体是何种形式,这就决定于开发者怎样编写这个 shortcode 了。
[myshortcode]Some Content[/myshortcode] // 封闭标签[myshortcode] // 自闭标签[myshortcode style="margin: 0px; padding: 0px; line-height: 25.2px; width: 660px; overflow: hidden; clear: both;"> function myshortcode_function($atts, $content = null){ // $atts 代表了 shortcode 的各个参数,$content 为标签内的内容 extract(shortcode_atts(array( // 使用 extract 函数解析标签内的参数 "title" => '标题' // 给参数赋默认值,下面直接调用 $ 加上参数名输出参数值 ), $atts)); // 返回内容 return '<div class="myshortcode"> <h3>'. $title .'</h3> <p> '. $content .' </p> </div>';} add_shortcode("msc", "myshortcode_function"); // 注册该 shortcode,以后使用 [msc] 标签调用该 shortcode
把上面的代码添加到 functions.php 中,一个简单的 shortcode 便创建好了,我们可以通过 [msc][/msc]标签调用该 shortcode ,如:
[msc style="margin: 0px; padding: 0px; line-height: 25.2px; width: 660px; overflow: hidden; clear: both;"> function myshortcode_function($atts, $content = null){ // $atts 代表了 shortcode 的各个参数,$content 为标签内的内容 extract(shortcode_atts(array( // 使用 extract 函数解析标签内的参数 "title" => '标题' // 给参数赋默认值,下面直接调用 $ 加上参数名输出参数值 ), $atts)); // 返回内容 return '<div class="myshortcode"> <h3>'. $title .'</h3> <p> '. $content .' </p> </div>';} add_shortcode("msc", "myshortcode_function"); // 注册该 shortcode,以后使用 [msc] 标签调用该 shortcode
msc 即为短代码名,以后在写文章或页面时可以直接使用 [msc][/msc] 标签调用该短代码,而 "myshortcode_function" 即为例子中的短代码处理函数的名称。下面重点分析短代码处理函数。
五.短代码处理函数
shortcode 处理函数是一个 shortcode 的核心, shortcode 处理函数类似于 Flickr(WordPress 过滤器),它们都接受特定参数,并返回一定的结果。 shortcode 处理器接受两个参数, $attr 和 $content , $attr 代表 shortcode 的各个属性参数,从本质上来说是一个关联数组,而 $content 代表 shortcode 标签中的内容。
如上面的例子,若在文章内作出调用,输出一段欢迎语句:
[msc style="margin: 0px; padding: 0px; line-height: 25.2px; width: 660px; overflow: hidden; clear: both;">
array( 'title' => '欢迎')
shortcode_atts() 包含两个参数 $defaults_array 与 $atts , $attr 即为属性参数集合, $defaults_array 是代表需要设置的属性默认值,举个例子:
'title' 由于在 $defaults_array 有不同的值,因此以这个新的值为准更新了 'title' ,同时也增加了 'description' 这个值。值得注意的是, shortcode_atts() 会过滤 $defaults_array 中没有的属性,假如 $attr 中还有一个 'ohter' 的属性,那么 $result 的结果仍然是上面的结果,因为 $defaults_array 中并没有 'other' 这个属性。当然,这里说的值只是属性的默认值,真正输出的值还是 shortcode 调用时填写的值。
extract() 函数用于进一步解析属性并设置属性默认值,其中一个功能是把各属性参数值赋予给一个形如 "$参数名" 的变量保存起来(如例子中的 $title ),方便调用,使用该函数配合 shortcode_atts() 就可以很安全的输出结果。这点的具体使用可以参见本文第一点“一.函数 add_shortcode”的例子。