关于 WordPress Shortcode 以及在 the_content 之外使用

Wordpress 中可以用 Shortcode 来创建宏代码,并且是高度可定制的,例如,有 PHP 代码:

 1// [bartag foo="foo-value"]
 2function bartag_func($atts) {
 3    extract(shortcode_atts(array(
 4        'foo' => 'no foo',
 5        'bar' => 'default bar',
 6    ), $atts));
 7
 8    return "foo = {$foo}";
 9}
10add_shortcode('bartag', 'bartag_func');

那么只要在你的 post 中输入,[bartag foo="foo-value"],显示该文章的时候此处就被 bartag_func() 函数替换为:foo = foo-value。来个更实用的,比如欲定义一个[unmi_blog] 的标签,定义代码写成如下:
1// [unmi_blog]
2function unmi_blog_func($atts) {
3    return "<a href='http://unmi.cc'>隔叶黄莺 The Blog of Unmi</a>";
4}
5add_shortcode('unmi_blog', 'unmi_blog_func');

那么在文章中的 [unmi_blog] 的会显示为:隔叶黄莺 Unmi Blog

还能用 Shortcode 打照更强大的自定义标签,如 [YouTube id='1234'] 就显示 id=1234 的视频等等,只是 Shortcode 似乎又太局限了。在文中 http://codex.wordpress.org/Shortcode_API 详细介绍了 Shortcode 的用法,并且说在 the_content 显示的时候,Shortcode API 就会去解析已注册的 Shortcode,这就让 Shortcode 不能轻易的用在别处,不是在 post 里写 [unmi_blog] 将会原样显示出 [unmi_blog] 来,其实也就是在 Wordpress 系统里有:

add_filter('the_content', 'do_shortcode'); 

但是人是活的,那些代码原本就是人编写的,我们可以假以巧妙的 Hack 让 Shortcode 应用在别处。

1. Customer Field 中应用 Shortcode Parse Shortcodes in your Custom Fields
2. Sidebar 里的 Text Widget 中 Adding a Shortcode to a Sidebar Widget
3. 任意地方 $text = yourShortCodeFunction("[your shortcode tag here]");echo $text; 外大括号,里小括号
 1/*<?php wp_show_surveys(1);?>*/
 2function wp_show_survey($survey_id=''){
 3    $short_code = '[SURVEYS '.$survey_id . ']';
 4    $output = apply_filters('show_survey', $short_code);
 5    echo $output;
 6}
 7
 8add_filter('show_survey','do_shortcode');
 9
10function custom_show_survey($content=''){
11    //echo "<script>alert(123)</script>";
12    return $content;
13}
14
15//add_filter('show_survey','custom_show_survey');
参考: 1. Shortcode API 永久链接 https://yanbin.blog/wordpress-shortcode-location/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。