Shortcode 短代码在 wordpress 的运用介绍
Shortcode 是指在文章编辑中,插入一个以中括号 “[" 和 “]" 包覆的语法,例如 “[show_me_video]",wordpress 程式看到这些已经短代码时,就会依据所定义的内容做转换输出,和以往使用的 BBCode 非常相似,可以让你编辑文章时更加方便、程式码更简洁。
Shortcode 的定义非常简单,打开佈景的 functions.php
插入以下语法:
function foobar_func( $atts ){ return "foo and bar"; } add_shortcode( 'foobar', 'foobar_func' );
当我们在编辑文章时,在适当的位置填入[foobr],当网友看文章时,这一段短代码就会显示为"foo and bar"。
但是当我们想要增加一些变数输出时,我们就必须使用 shortcode_atts 这个函数。
用法:
shortcode_atts( $pairs , $atts, $shortcode );
$pairs: array、必须的。属性的定义值,如果没有输入任何属性时,显示定义值。
$atts: array、必须的。使用者输入的属性值。
$shortcode: string、非必须的。Shortcode 名称。
范例如下
function mylink_func( $atts ) { $a = shortcode_atts( array( 'link' => '#', 'name' => 'click me'), $atts ); return '<a href="' . $a['link'] . '">' . $a['name'] . '</a>'; } add_shortcode( 'mylink', 'mylink_func' );
在文章中插入 [mylink link=’http://www.abcde.com’ name="abcde网站"]
输出就会变成
<a href="http://www.abcde.com">abcde网站</a>
以上是 self-closing 方式呈现,不用写终止标签,像是 html 的 img 元素一样,不用结尾的标签。Shortcode 也有 Enclosing 型态,他的呈现也和一般 html 一样,例如:[my_short_code]中间内容[/my_short_code]。
Enclosing 型态的范例如下:
当你输入:
[my_caption]My Caption[/my_caption]
呈现的是:
<span class="caption">My Caption</span>
程式范例:
function caption_shortcode( $atts, $content = null ) { return '<span class="caption">' . $content . '</span>'; } add_shortcode( 'my_caption', 'caption_shortcode' );
(我们可以发现到他多了一个传入参数 $content = null )
shortcode 裡面又包一个 shortcode 的处理方式
当你输入:
[my_caption]Caption: [my_shortcode][/my_caption]
依照上面的程式,是不会处理中间的 [my_shortcode],这时候只要稍微修改,加入 do_shortcode 就可以了,
修改范例如下:
function caption_shortcode( $atts, $content = null ) { return '<span class="caption">' . do_shortcode($content) . '</span>'; }
若是想要让 shortcode 也能增加属性
[my_caption class="my_class"]Caption: [my_shortcode][/my_caption]
再次修改:
function caption_shortcode( $atts, $content = null ) { $a = shortcode_atts( array( 'class' => 'def_class' ), $atts ); return '<span class="'.$a['class'].'">' . do_shortcode($content) . '</span>'; }