Shortcode 指的是一些使用[ ]包含的短代码,WordPress会识别这些短代码并根据短代码的定义输出特定的内容。Shortcode API这个接口非常容易使用,并且功能非常强大,可以使用它在日志的内容中来给日志内容添加各种功能。
Shortcode 类型
Shortcode API 支持几乎所有可能的组合形式:自关闭标签,开放标签,含有参数的标签等。
[mycode]
[mycode foo="bar" id="123" color="red" something="data"]
[mycode]Some Content[/mycode]
[mycode]<p><a href="http://example.com/">HTML Content</a<>/p>[/mycode]
[mycode]Content [another-shotcode] more content[/mycode]
[mycode foo="bar" id="123"]Some Content[/mycode]
Shortcode的基本用法
首先你要去定义一个函数,来处理你定义的 Shortcode,和它的属性参数以及引用的内容。然后把自己定义的 Shortcode 和其处理函数管理起来,以便 [mycode attr="value"]content[/mycode] 能够按照预期执行。
function my_shortcode_func($attr, $content) {
// $attr $key=>$value 的数组
// $content 是 shortcode 中包含的字符串
// 对 $attr 和 $content 进行处理
// 返回预期的值
}
<pre class="php" style="font-family:monospace;">add_shortcode<span style="color:#009900;">(</span><span style="color:#0000ff;">'mycode'</span><span style="color:#339933;">,</span> <span style="color:#0000ff;">'my_shortcode_func'</span><span style="color:#009900;">)</span>
Shortcode 的有关函数
add_shortcode('mycode', 'function_name'); // 定义一个新的 Shortcode
remove_shortcode('mycode'); // 移除一个 Shortcode
remove_all_shortcodes(); // 移除所有的 Shortcode
$return = do_shortcode($content); // 应用 Shortcode 到内容而不输出
在侧边栏 Widgets 中使用 Shortcode
Shortcode 很方便,但是只能用在日志内容中,那么如何在 WordPress 的侧边栏的 Widgets 中使用 Shortcode,在当前主题的 functions.php
中添加如下代码:
add_filter('widget_text', 'do_shortcode');
然后你在 WordPress 后台 > 外观 > Widgets 界面添加一个文本 Widget,然后插入博客中经启用 shortcode 即可。
在主题的文件中使用 Shortcode
如果你想用在主题文件中使用名为 [my_shortcode] 的 Shortcode,你只需要按照下面的方式使用do_shortcode()
函数即可:
<?php echo do_shortcode("[my_shortcode]"); ?>
以上便是shortcode的使用方法了!