更新日期:2014-10-23

前兩個教學都是以 self-closing 方式呈現,不用寫終止標籤,像是 html 的 img 元素一樣,不用結尾的標籤。Shortcode 也有 Enclosing 型態,他的呈現也和一般 html 一樣,例如:[my_short_code]中間內容[/my_short_code]。

 

Enclosing 型態的範例如下:

當你輸入:
[code]
[my_caption]My Caption[/my_caption]
[/code]
 
呈現的是:
[code]
<span class="caption">My Caption</span>
[/code]
 
程式範例:
[code language=”php”]
function caption_shortcode( $atts, $content = null ) {
return ‘<span class="caption">’ . $content . ‘</span>’;
}
add_shortcode( ‘my_caption’, ‘caption_shortcode’ );
[/code]
(我們可以發現到他多了一個傳入參數 $content = null )

 

shortcode 裡面又包一個 shortcode 的處理方式

當你輸入:
[code]
[my_caption]Caption: [my_shortcode][/my_caption]
[/code]
依照上面的程式,是不會處理中間的 [my_shortcode],這時候只要稍微修改,加入 do_shortcode 就可以了,
修改範例如下:
[code language=”php”]
function caption_shortcode( $atts, $content = null ) {
return ‘<span class="caption">’ . do_shortcode($content) . ‘</span>’;
}
[/code]

 

若是想要讓 shortcode 也能增加屬性

[code]
[my_caption class="my_class"]Caption: [my_shortcode][/my_caption]
[/code]
 
再次修改:
[code language=”php”]
function caption_shortcode( $atts, $content = null ) {
$a = shortcode_atts(
array( ‘class’ => ‘def_class’ ),
$atts
);
return ‘<span class="’.$a[‘class’].’">’ . do_shortcode($content) . ‘</span>’;
}
[/code]

 
 

所有 Shortcode 相關文章

一、Shortcode 短代碼在 wordpress 的運用介紹
二、Shortcode 短代碼增加屬性的方法
三、Shortcode 短代碼 Enclosing 型態