所有分类
  • 所有分类
  • 其它

WORDPRESS SHORTCODE(简码)介绍及使用详解

WordPress 从 2.5 版本开始增加了一个类似 BBCode 标签的 Shortcode API,可以使用它在日志的内容中来给日志内容添加各种功能。Shortcode 这个接口非常容易使用,并且功能非常强大。

简单说 WordPress Shortcode 指的是一些使用[]包含的短代码,WordPress会识别这些短代码并根据短代码的定义输出为特定的内容。

Shortcode 类型

Shortcode API 支持几乎所有可能的组合形式:自关闭标签,开放标签,含有参数的标签等。

[mycode]
[mycode foo="bar" id="123" color="red" something="data"]
[mycode]Some Content[/mycode]
[mycode]

HTML Content/p>[/mycode] [mycode]Content [another-shotcode] more content[/mycode] [mycode foo=”bar” id=”123″]Some Content[/mycode]


Shortcode 基本概念

首先你要去定义一个函数,来处理你定义的 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')

Shortcode 相关的所有函数

WordPress 定义了以下和 Shortcode 相关的函数:

add_shortcode('mycode', 'function_name'); // 定义一个新的 Shortcode
remove_shortcode('mycode'); // 移除一个 Shortcode
remove_all_shortcodes(); // 移除所有的 Shortcode
$return = do_shortcode($content); // 应用 Shortcode 到内容而不输出

一个简单的 Shortcode 例子

以我爱水煮鱼写的 Antispambot ShortCode 插件为例,内容就是邮箱地址,有个参数 $link 为 1 时候,把邮箱显示可点击,参数如下:

function antispambot_shortcode_handler($atts, $content='') {
	extract( shortcode_atts( array(
		'link' => '0'
	), $atts ) );
 
	if($link){
		return ''.antispambot($content,0).'';
	}else{
		return antispambot( $content,0);
	}
}
add_shortcode('email', 'antispambot_shortcode_handler');

使用 Shortcode 投放 Google Adsense 广告

把下面的代码保存到你当前的主题的 functions.php,或者上传到插件目录下并激活。


解决 Shortcode 中自动添加的 br 或者 p 标签

我们在使用 WordPress Shortcode API 开发插件的时候,有个比较麻烦的问题,就是 WordPress 会自动在 shortcode 内添加 br 或者 p 标签,这样可能会打乱你的原先预想的 HTML 结构和布局。

造成这个问题的原因是 WordPress 默认的日志内容处理流程中,wpautop(将回车转换成 p 或者 br 标签的函数)是在 Shortcode 前面运行的。所以我们的解决方案也是非常简单,改变它们执行的顺序,在当前主题的 functions.php 文件中添加:

remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 12);

这样调整顺序之后,你的 shortcode 里面的内容,就不会有自动添加的 p 或者 br 标签,但是如果 shortcode 中部分的内容你又需要一些 p 或者 br 标签用来换行的话,你需要自己手动在自己 shortcode 处理程序中添加 wpautop 来处理了。

function bio_shortcode($atts, $content = null) {
   $content = wpautop(trim($content));
   return '
‘ . $content . ‘

‘; } add_shortcode(‘bio’, ‘bio_shortcode’);

显示验证码

社交账号快速登录