WordPress 從 2.5 的版本開始,增加了一個(gè) shortcode (短代碼) API,類似于 BBS 上的 BBCode,shortcode 也可以很方便的為文章或頁(yè)面增加功能,并且 shortcode 的比起 BBCode 更加靈活和強(qiáng)大,下面MK為大家介紹一下shortcode.
一.shortcode 簡(jiǎn)介
shortcode 可以讓開發(fā)者通過以函數(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 title="example"] // 帶有一個(gè)參數(shù)的自閉標(biāo)簽
- [myshortcode]<p><a href="#"><span>內(nèi)容</span></a></p>[/myshortcode] // 標(biāo)簽內(nèi)可以填寫文本或 HTML
- [myshortcode]Content [myshortcodesecond] more content[/myshortcodesecond] // 也可以嵌套
三.shortcode 例子
在使用 shortcode 前,首先必須在主題的 functions.php 文件中定義 shortcode,例如,代碼如下:
- 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ù)值 //Vevb.com
- ), $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)建好了,我們可以通過 [msc][/msc]標(biāo)簽調(diào)用該 shortcode,代碼如下:
[msc title="歡迎"]這是明凱博客,歡迎來(lái)到本博客[/msc]
在文章或頁(yè)面內(nèi)容中輸入上面的調(diào)用,可以在相應(yīng)的位置輸出一段歡迎語(yǔ)句,在 style.css 中定義相應(yīng)的 CSS,即可為短代碼賦予樣式.
|
新聞熱點(diǎn)
疑難解答
圖片精選