WordPress 從 2.5 的版本開始,增加了一個(gè) shortcode (短代碼) API ,類似于 BBS 上的 BBCode , shortcode 也可以很方便的為文章或頁(yè)面增加功能,并且 shortcode 的比起 BBCode 更加靈活和強(qiáng)大。下面 Kayo 為大家介紹一下 shortcode 。
一.shortcode 簡(jiǎn)介
shortcode 可以讓開發(fā)者通過(guò)以函數(shù)的形式創(chuàng)建宏內(nèi)容來(lái)生成內(nèi)容,或許這個(gè)概念看上去有點(diǎn)模糊,但實(shí)際上它是一個(gè)很簡(jiǎn)單而實(shí)用的功能,只要會(huì)編寫基本的 PHP 函數(shù),即可使用 shortcode ,下文會(huì)以實(shí)際的例子來(lái)說(shuō)明 shortcode 的使用方法。
二.shortcode 形式
shortcode 支持封閉標(biāo)簽和自閉(自動(dòng)封閉)標(biāo)簽,并且支持在標(biāo)簽內(nèi)使用參數(shù),至于 shortcode 具體是何種形式,這就決定于開發(fā)者怎樣編寫這個(gè) shortcode 了。
[myshortcode]Some Content[/myshortcode] // 封閉標(biāo)簽[myshortcode] // 自閉標(biāo)簽[myshortcode style="margin: 0px; padding: 0px; line-height: 25.2px; width: 660px; overflow: hidden; clear: both;"> function myshortcode_function($atts, $content = null){ // $atts 代表了 shortcode 的各個(gè)參數(shù),$content 為標(biāo)簽內(nèi)的內(nèi)容 extract(shortcode_atts(array( // 使用 extract 函數(shù)解析標(biāo)簽內(nèi)的參數(shù) "title" => '標(biāo)題' // 給參數(shù)賦默認(rèn)值,下面直接調(diào)用 $ 加上參數(shù)名輸出參數(shù)值 ), $atts)); // 返回內(nèi)容 return '<div class="myshortcode"> <h3>'. $title .'</h3> <p> '. $content .' </p> </div>';} add_shortcode("msc", "myshortcode_function"); // 注冊(cè)該 shortcode,以后使用 [msc] 標(biāo)簽調(diào)用該 shortcode 把上面的代碼添加到 functions.php 中,一個(gè)簡(jiǎn)單的 shortcode 便創(chuàng)建好了,我們可以通過(guò) [msc][/msc]標(biāo)簽調(diào)用該 shortcode ,如:
[msc style="margin: 0px; padding: 0px; line-height: 25.2px; width: 660px; overflow: hidden; clear: both;"> function myshortcode_function($atts, $content = null){ // $atts 代表了 shortcode 的各個(gè)參數(shù),$content 為標(biāo)簽內(nèi)的內(nèi)容 extract(shortcode_atts(array( // 使用 extract 函數(shù)解析標(biāo)簽內(nèi)的參數(shù) "title" => '標(biāo)題' // 給參數(shù)賦默認(rèn)值,下面直接調(diào)用 $ 加上參數(shù)名輸出參數(shù)值 ), $atts)); // 返回內(nèi)容 return '<div class="myshortcode"> <h3>'. $title .'</h3> <p> '. $content .' </p> </div>';} add_shortcode("msc", "myshortcode_function"); // 注冊(cè)該 shortcode,以后使用 [msc] 標(biāo)簽調(diào)用該 shortcode msc 即為短代碼名,以后在寫文章或頁(yè)面時(shí)可以直接使用 [msc][/msc] 標(biāo)簽調(diào)用該短代碼,而 "myshortcode_function" 即為例子中的短代碼處理函數(shù)的名稱。下面重點(diǎn)分析短代碼處理函數(shù)。
五.短代碼處理函數(shù)
shortcode 處理函數(shù)是一個(gè) shortcode 的核心, shortcode 處理函數(shù)類似于 Flickr(WordPress 過(guò)濾器),它們都接受特定參數(shù),并返回一定的結(jié)果。 shortcode 處理器接受兩個(gè)參數(shù), $attr 和 $content , $attr 代表 shortcode 的各個(gè)屬性參數(shù),從本質(zhì)上來(lái)說(shuō)是一個(gè)關(guān)聯(lián)數(shù)組,而 $content 代表 shortcode 標(biāo)簽中的內(nèi)容。
如上面的例子,若在文章內(nèi)作出調(diào)用,輸出一段歡迎語(yǔ)句:
[msc style="margin: 0px; padding: 0px; line-height: 25.2px; width: 660px; overflow: hidden; clear: both;">
array( 'title' => '歡迎')















