LoginSignup
11
15

More than 5 years have passed since last update.

【Wordpress】ショートコードの作成方法

Last updated at Posted at 2015-08-22

作成方法

便利ショートコードを追加できるプラグインはたくさんあるけど、もうちょっとこうしたいんだよな〜って時がある。

そういった場合は、ショートコードを自作しちゃおう。
例えば、ボタン専用のショートコードを作成したい場合は、functions.phpに以下のように記述するだけ。
これだけでショートコードが作成できる。

functions.php
function shortcode_buttun($arg) {
    extract(shortcode_atts(array (
        'text' => 'お問い合わせ',
        'href' => './',
        'target' => '',
        'type' => 'default'
    ), $arg));
    if($target != '') $target = ' target="'.$target.'"';
  return '<button class="l-btn type-'.$type.'"><a href="'.$href.'"'.$target.'>'.$text.'</a></button>';
}

add_shortcode('button', 'shortcode_buttun');

使い方

functions.phpにショートコード作成のコードを記述したら、投稿ページなどで使用できる。

デフォルトのまま使いたい場合
[button]

引数を指定する場合
[button text=送信! href=http://~ target=_brank]

get_template_part()を使う場合

get_template_part() は 'require_once()' でロードしているため、投稿の一番上に表示されてしまいます。
ob_start() を使い、レンダリングのバッファを取得しておくことで、ショートコードが呼び出されたタイミングでテンプレートを表示することができます。

/**
 * LPフォームテンプレートを呼び出すショートコード
 * @return [type] [description]
 */
function hoge_template_shortcode() {
  ob_start();
  get_template_part('./template/hoge');

  return ob_get_clean();
}
add_shortcode('hoge_template', 'hoge_template_shortcode');

参考

11
15
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
11
15