2010-04-27 | 阅读(671)	
WordPress 中可以用 Shortcode 来创建宏代码,并且是高度可定制的,例如,有 PHP 代码:
		
		
			
			
				
					
				|  | // [bartag foo="foo-value"] function bartag_func($atts) {     extract(shortcode_atts(array(         'foo' => 'no foo',         'bar' => 'default bar',     ), $atts));       return "foo = {$foo}"; } add_shortcode('bartag', 'bartag_func'); | 
				
			 
		 
那么只要在你的 post 中输入,[bartag foo="foo-value"],显示该文章的时候此处就被 bartag_func() 函数替换为:foo = foo-value。来个更实用的,比如欲定义一个[unmi_blog] 的标签,定义代码写成如下:
		
		
			
			
				
					
				|  | // [unmi_blog] function unmi_blog_func($atts) {     return "<a href='http://unmi.cc'>隔叶黄莺 The Blog of Unmi</a>"; } add_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; 外大括号,里小括号
 /*<?php wp_show_surveys(1);?>*/
 function wp_show_survey($survey_id=''){
  $short_code = '[SURVEYS '.$survey_id . ']';
  $output = apply_filters('show_survey', $short_code);
  echo $output;
 }
add_filter('show_survey','do_shortcode');
function custom_show_survey($content=''){
 //echo "<script>alert(123)</script>";
 return $content;
}
//add_filter('show_survey','custom_show_survey');
参考: 1. Shortcode API