WordPressでショートコードを作成

固定ページの中で他の固定ページにリンクを貼るためにショートコードを作成しました。extract()で配列を変数として返していますが、/wp-includes/shortcodes.phpに記載されているサンプルコードを見ると$attsをそのまま使うほうが良いのかもしれません。

<?php
function page_link_func($atts) {
    extract(shortcode_atts(array(
        'id' => 1,
        'title' => 'リンク',
    ), $atts));

    return '<a href="' . get_page_link($id) . '" target="_blank">' . $title . '</a>';
}
add_shortcode('page_link', 'page_link_func');

ショートコードの呼び出し

[page_link id="123" title="ページリンク"]

$attsをvar_dumpすると引数で指定した値が格納されています。

array(2) { ["id"]=>"123" ["title"]=> "ページリンク" }

add_shortcode()は/wp-includes/shortcodes.phpで定義されていて、指定したタグをキーにしてショートコードを連想配列に格納します。

<?php
function add_shortcode($tag, $func) {
    global $shortcode_tags;

    if ( is_callable($func) )
        $shortcode_tags[$tag] = $func;
}

shortcode_atts()はショートコードで引数が指定されていなかった場合に、指定した値を初期値に設定して返します。

<?php
function shortcode_atts( $pairs, $atts, $shortcode = '' ) {
    $atts = (array)$atts;
    $out = array();
    foreach($pairs as $name => $default) {
        if ( array_key_exists($name, $atts) )
            $out[$name] = $atts[$name];
        else
            $out[$name] = $default;
    }
    if ( $shortcode )
        $out = apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts );

    return $out;
}

ショートコードを作成する度に、初期値の設定用にshortcode_atts()の処理を書くのは面倒なので、メソッドの引数で初期化できると楽になりそうな気がします。