WordPress Shortcode 指的是一些使用 ⌈⌋ 包含的短代码,WordPress 会识别这些短代码并根据短代码的定义输出为特定的内容,Shortcode API 这个功能是 WordPress 从 2.5 版本开始引入的,使用它可以给日志内容添加各种功能,并且 Shortcode 这个接口非常容易使用,并且功能非常强大。
为保证本文内容的完整性,防止短代码被 WordPress 自动翻译,本文中所有涉及到的方括号([])都使用 ⌈⌋ 代替。
Shortcode API 支持几乎所有可能的组合形式:自关闭标签、开放标签、含有参数的标签等。
- ⌈mycode⌋
- ⌈mycode foo="bar" id="123" color="red" something="data"⌋
- ⌈mycode⌋Some Content⌈/mycode⌋
- ⌈mycode⌋<p><a href="http://www.cdsy.com.cn/">HTML Content</a>/p>/mycode
- ⌈mycode⌋Content another-shotcode more content/mycode
- ⌈mycode foo="bar" id="123"⌋Some Content/mycode
首先你要去定义一个函数,来处理你定义的 Shortcode,和它的属性参数以及引用的内容。
- function my_shortcode_func($attr, $content) {
- // $attr $key=>$value 的数组
- // $content 是 shortcode 中包含的字符串
- // 对 $attr 和 $content 进行处理
- // 返回预期的值
- }
然后把自己定义的 Shortcode 和其处理函数管理起来,以便 ⌈mycode attr="value"⌋content⌈/mycode⌋ 能够按照预期执行。
- add_shortcode('mycode', 'my_shortcode_func')
WordPress 定义了以下和 Shortcode 相关的函数:
它定义 ⌈email⌋ 这个 Shortcode,将用户输入的 email地址转义成 HTML 实体,防止机器抓取,它的内容($content)就是邮箱地址,还定义了属性 $link,它的值为 1 时候,邮箱显示为可点击,详细代码如下:
- function antispambot_shortcode_handler($atts, $content='') {
- extract( shortcode_atts( array(
- 'link' => '0'
- ), $atts ) );
- if($link){
- return '<a href="mailto:'.antispambot($content,1).'" title="mail to '.antispambot($content,0).'">'.antispambot($content,0).'</a>';
- }else{
- return antispambot( $content,0);
- }
- }
- add_shortcode('email', 'antispambot_shortcode_handler');