更新日期:2022-04-12

之前介紹了基本的 Shortcode 的運用,但是當我們想要增加一些變數輸出時,我們就必須增加使用 shortcode_atts 這個函數。

語法:

shortcode_atts( $pairs, $atts, $shortcode );

參數介紹:

$pairs: array、必須的。屬性的定義值,如果沒有輸入任何屬性時,顯示定義值。
$atts: array、必須的。使用者輸入的屬性值。
$shortcode: string、非必須的。Shortcode 名稱。

完整語法:

function bartag_func( $atts ) {
    $atts = shortcode_atts(
        array(
            'link' => 'https://www.com',
            'name' => 'my name',
        ), 
        $atts, 
        'bartag' 
    );
 
    return '<a href="' . $atts['link'] . '">' . $atts['name'] . '</a>';
}

add_shortcode( 'bartag', 'bartag_func' );

用法:

[bartag link='http://www.abcde.com' name="abcde"]

輸出:

<a href="http://www.abcde.com">abcde</a>

其他 Shortcode 相關文章

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