LoginSignup
6
5

More than 5 years have passed since last update.

【WordPress】ショートコードの書き方

Posted at

markdown記法でもいいんだけど、ちょっとカスタマイズしたいとか、色々処理を施したいとか、そういうののためのショートコードの書き方です。
ほぼ自分用のメモなので雑な書き方ですみません。

ショートコードは[ ]で囲んで書きます。
[ショートコード名 属性名1=値1 属性名2=値2]みたいな書き方です。
また、[ショートコード名 属性名=値]文字列など[/ショートコード名]というふうにも書けます。

投稿記事
[banner img="banner1.png"]案内ページ[/banner]

そしてこのショートコードをfunctions.phpで定義します。

functions.php
function make_banner($atts, $content = 'バナー') {
    extract(shortcode_atts(array(
    'img' => 'banner_noimage.png'
    ), $atts));

    $src = get_template_directory_uri().'/images/'.$img;
    return '<img class="banner" src="'.$src.'" alt="'.$content.'">';
}
add_shortcode('banner', 'make_banner');

\$attsには属性名と属性値の入力が、\$contentには挟まれた文字列が入ります(\$content = xx でデフォルトの値を設定します)
extract...の部分で、属性名の変数(\$img)に得た値を代入し、入力値がない場合にはデフォルト値(例の場合なら'banner_noimage.png')を代入します。

例の場合の出力結果は
<img class="banner" src="http://hogehoge.com/wordpress/wp-content/themes/original_theme/images/banner1.png" alt="案内ページ">
のようになります。

6
5
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
6
5