LoginSignup
1
0

More than 1 year has passed since last update.

【WordPress】自作ショートコードの定義

Posted at

依頼に応じてショートコードを作成することがあるのですが、
なにぶんよく書き方を忘れるので、ひな形を備忘録として残します。

シンプルなショートコードの定義

決められた文字列を返すだけのどシンプルなショートコード

functions.php
function hoge_func() {
    return "Hello World";
}
add_shortcode('hoge', 'hoge_func');
WordPress.設定
[hoge]

引数を渡して実行するショートコード

1つの引数を渡す場合

functions.php
function hoge_func($atts) {
    extract(shortcode_atts(array(
        'num' => 0,
    ), $atts));

    return $num * 2;
}
add_shortcode('hoge', 'hoge_func');

「'num' => 0」で変数「num」に初期値「0」を代入する。
※引数が渡されなかった場合、「0」が設定される。

WordPress.設定
[hoge num=1]

2つ以上の引数を渡す場合

functions.php
function hoge_func($atts) {
    extract(shortcode_atts(array(
        'num1' => 0,
        'num2' => 0,
        'num3' => 0,
    ), $atts));

    return $num1 + $num2 + $num3;
}
add_shortcode('hoge', 'hoge_func');

※初期値の設定を追加するだけ

WordPress.設定
[hoge num1=1 num2=2 num3=3]

複数の引数を渡す際は、半角スペースを挟んで記述する。

囲み型のショートコード

文字列を囲った形で使用したい際に使う。

functions.php
function hoge_func($atts, $content = null) {
    return '<h1>' . $content . '</h1>';
}
add_shortcode('hoge', 'hoge_func');
WordPress.設定
[hoge]Hello World[/hoge]

囲まれた文字列が「$content」に入る。
※文字列だけでなくGutenbergのブロック要素を囲っても動作可能。

囲み型で引数を渡す場合

functions.php
function hoge_func($atts, $content = null) {
    extract( shortcode_atts( array(
        'class' => 'default',
    ), $atts ) );

    return '<h1 class="' . $class . '">' . $content . '</h1>';
}
add_shortcode('hoge', 'hoge_func');

引数に関する書き方は自己完結型のものと同じ。

WordPress.設定
[hoge class="class-name"]Hello World[/hoge]

テンプレート(PHPファイル内)からショートコードを呼び出す場合

template.php
<?php echo do_shortcode('[hoge]'); ?>

ショートコードは基本的に投稿や固定ページで記述するものだが、
テンプレート等のPHPファイルから実行も可能。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0