简码支持各种格式的属性,接受给简码回调函数的第一个参数。如果你要给参数设置默认值,可以使用 shortcode_atts() 函数:
function Bing_shortcode_test( $attr, $content ){ extract( shortcode_atts( array( 'url' => 'http://www.bgbk.org', 'hide' => false, 'text' => '点击隐藏 / 显示' ), $attr ) ); $hide = $hide ? ' style="display:none;"' : ''; return '<a ' . $hide . '>' . $text . '</a>'; } add_shortcode( 'test', 'Bing_shortcode_test' );
只有页面中使用了简码的时候才加载脚本
而在开发的过程中,有时会遇到这种问题:简码模块需要加载 JS 或者 CSS 脚本,而当页面没有使用简码的时候就会造成资源浪费。
比如下边的这个 Google 地图插件:
//添加简码 function Bing_add_google_map( $atts, $content ){ //content... } add_shortcode( 'google_map', 'Bing_add_google_map'); //挂载脚本 function Bing_add_javascript(){ wp_enqueue_script( 'map_scripts' ); } add_action( 'wp_enqueue_scripts', 'Bing_add_javascript' );
只有在页面中使用了 [google_map] 简码的时候才需要加载脚本,这怎么做到呢?
其实很简单,只需要在简码函数触发的时候在页脚挂载脚本即可。
//添加简码 function Bing_add_google_map( $atts, $content ){ $GLOBALS['google_map_shortcode'] = true; return '地图的代码'; } add_shortcode( 'google_map', 'Bing_add_google_map'); //挂载脚本 function Bing_add_javascript(){ global $google_map_shortcode; if( isset( $google_map_shortcode ) && $google_map_shortcode ) wp_enqueue_script( 'map_scripts' ); } add_action( 'wp_footer', 'Bing_add_javascript' );
总结
简码是个非常强大的功能,对文章内容是一种很好的扩展,利用好可以让添加某些东西变的方便快捷。
关于简码的函数都在:wp-includes/shortcode.php 文件里,有能力的朋友可以阅读一下,了解原理。
标签:WordPress
相关阅读 >>
wordpress dynamic_sidebar()函数使用方法
wordpress 为主题添加ajax提交评论功能的php代码
对帝国cms、dedecms、phpcms、discuz、phpwind、xiuno负载测试总结
更多相关阅读请进入《wordpress》频道 >>