[msc id="codetool">
在文章或页面内容中输入上面的调用,可以在相应的位置输出一段欢迎语句,在 style.css 中定义相应的 CSS ,即可为短代码赋予样式。
Kayo 简略的介绍了 WordPress 的短代码(shortcode) 功能,主要是介绍了 shortcode 的主要概念和使用方法。在本文中, Kayo 将会更加详细的介绍一下 shortcode 中较为重要的 API ,希望有助于各位开发较为复杂的 shortcode 。
四.函数 add_shortcode
该函数用于注册一个 shortcode ,它有两个参数:短代码名与 shortcode 处理函数名,引用上文的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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 php” id=”highlighter_111994″>
1 |
array ( 'title' => '欢迎' ) |
在输出结果时,可以直接使用 $参数名 的形式进行输出,如例子中的情况即以 $title 输出该属性值。
六.shortcode_atts
shortcode_atts 是一个很实用的函数,它可以为你需要的属性参数设置默认值,并且删除一些不需要的参数。
shortcode_atts() 包含两个参数 $defaults_array 与 $atts , $attr 即为属性参数集合, $defaults_array 是代表需要设置的属性默认值,举个例子:
1 2 3 4 5 6 7 |
$result = shortcode_atts( array ( 'title' => '新标题' , 'description' => '描述内容' ), $atts ); $attr 依然为 array ( 'title' => '欢迎' ) |
这时 $result 的结果为
1 |
array ( 'title' => '新标题' , 'description' => '描述标题' ) |
‘title’ 由于在 $defaults_array 有不同的值,因此以这个新的值为准更新了 ‘title’ ,同时也增加了 ‘description’ 这个值。值得注意的是, shortcode_atts() 会过滤 $defaults_array 中没有的属性,假如 $attr 中还有一个 ‘ohter’ 的属性,那么 $result 的结果仍然是上面的结果,因为 $defaults_array 中并没有 ‘other’ 这个属性。当然,这里说的值只是属性的默认值,真正输出的值还是 shortcode 调用时填写的值。
七.进一步解析属性与设置属性默认值
extract() 函数用于进一步解析属性并设置属性默认值,其中一个功能是把各属性参数值赋予给一个形如 “$参数名” 的变量保存起来(如例子中的 $title ),方便调用,使用该函数配合 shortcode_atts() 就可以很安全的输出结果。这点的具体使用可以参见本文第一点“一.函数 add_shortcode”的例子。
另外,属性名中的大写字母在传递给处理函数前会先转化为小写字母,因此建议在编写属性名时直接使用小写字母。
|