2026年8月12日
2026年8月12日
WordPressでショートコードを作成する方法・add_shortcode()完全ガイド
はじめに
「記事中に[contact_form]と書くだけでフォームを表示したい」「特定のデザインブロックを簡単に挿入できるようにしたい」——ショートコードを使えば、複雑なHTMLやPHPロジックを簡単なタグで呼び出せます。
症状・原因
WordPressのショートコードは[tag]または[tag attr="value"]コンテンツ[/tag]形式で記事中に挿入できます。テーマやプラグインで登録されていないショートコードは、そのままテキストとして表示されてしまいます。適切にadd_shortcode()で登録する必要があります。
解決手順
ステップ1:基本的なショートコードを作成する
// functions.php に追加
// [my_button]
add_shortcode( 'my_button', function( $atts, $content = null ) {
// 属性のデフォルト値を設定
$atts = shortcode_atts( [
'url' => '#',
'color' => 'blue',
'target' => '_self',
], $atts, 'my_button' );
$url = esc_url( $atts['url'] );
$color = sanitize_html_class( $atts['color'] );
$target = in_array( $atts['target'], [ '_self', '_blank' ], true )
? $atts['target'] : '_self';
$label = $content ? esc_html( $content ) : 'クリック';
return '<a href="' . $url . '" class="btn btn-' . $color . '"'
. ' target="' . esc_attr( $target ) . '">'
. $label . '</a>';
} );
// 使用例: [my_button url="https://example.com" color="red" target="_blank"]詳しくはこちら[/my_button]
ステップ2:複雑なショートコードをクラスで管理する
class My_Shortcodes {
public function __construct() {
add_shortcode( 'pricing_table', [ $this, 'pricing_table' ] );
add_shortcode( 'staff_list', [ $this, 'staff_list' ] );
add_shortcode( 'recent_posts', [ $this, 'recent_posts' ] );
}
public function pricing_table( $atts ) {
$atts = shortcode_atts( [
'plan' => 'basic',
'price' => '0',
'currency' => '¥',
], $atts, 'pricing_table' );
ob_start(); // 出力バッファリングでHTMLを取得
?>
<div class="pricing-table pricing-<?php echo esc_attr( $atts['plan'] ); ?>">
<div class="price"><?php echo esc_html( $atts['currency'] . number_format( (int) $atts['price'] ) ); ?>/月</div>
</div>
<?php
return ob_get_clean();
}
public function recent_posts( $atts ) {
$atts = shortcode_atts( [
'count' => 5,
'category' => '',
], $atts, 'recent_posts' );
$args = [
'posts_per_page' => (int) $atts['count'],
'post_status' => 'publish',
];
if ( $atts['category'] ) {
$args['category_name'] = sanitize_text_field( $atts['category'] );
}
$posts = get_posts( $args );
$html = '<ul class="recent-posts">';
foreach ( $posts as $post ) {
$html .= '<li><a href="' . get_permalink( $post ) . '">'
. esc_html( $post->post_title ) . '</a></li>';
}
$html .= '</ul>';
wp_reset_postdata();
return $html;
}
}
new My_Shortcodes();
ステップ3:ショートコード内でアセットを読み込む
// ショートコードが使われた場合のみCSSを読み込む
add_shortcode( 'my_slider', function( $atts ) {
// ショートコード使用時にのみアセットをエンキュー
wp_enqueue_style(
'my-slider-css',
get_stylesheet_directory_uri() . '/assets/slider.css',
[],
'1.0.0'
);
wp_enqueue_script(
'my-slider-js',
get_stylesheet_directory_uri() . '/assets/slider.js',
[ 'jquery' ],
'1.0.0',
true // フッターに読み込み
);
// スライダーのHTMLを生成
ob_start();
include get_stylesheet_directory() . '/template-parts/slider.php';
return ob_get_clean();
} );
ステップ4:ショートコードをウィジェット・テンプレートでも使う
// テンプレートファイルでショートコードを実行
echo do_shortcode( '[my_button url="/contact" color="green"]お問い合わせ[/my_button]' );
// ウィジェットでショートコードを有効化
add_filter( 'widget_text', 'do_shortcode' );
add_filter( 'widget_text_content', 'do_shortcode' );
// ACFカスタムフィールドのテキストエリアでも有効化
add_filter( 'acf/format_value/type=textarea', 'do_shortcode', 20 );
// メニュータイトルでショートコードを有効化
add_filter( 'nav_menu_item_title', 'do_shortcode' );
ステップ5:Gutenbergブロックへの移行を検討する
// ショートコードをGutenbergブロックとして登録(推奨)
add_action( 'init', function() {
if ( ! function_exists( 'register_block_type' ) ) return;
register_block_type( 'myplugin/my-button', [
'attributes' => [
'url' => [ 'type' => 'string', 'default' => '#' ],
'color' => [ 'type' => 'string', 'default' => 'blue' ],
'label' => [ 'type' => 'string', 'default' => 'クリック' ],
],
'render_callback' => function( $attrs ) {
return '<a href="' . esc_url( $attrs['url'] ) . '"'
. ' class="btn btn-' . sanitize_html_class( $attrs['color'] ) . '">'
. esc_html( $attrs['label'] ) . '</a>';
},
] );
} );
// 古いショートコードコンテンツを変換するコマンド
// wp post list --post_type=post --format=ids | xargs -I{} wp eval '
// $post = get_post({});
// if (has_shortcode($post->post_content, "my_button")) {
// echo $post->ID . " has my_button shortcode\n";
// }
// '
注意事項
- ショートコードのコールバック関数は必ず文字列を返す(return)必要があります。
echoで出力するとページの意図しない場所に出力されます。 - ショートコードの属性値は必ず
sanitize_関数やesc_関数でサニタイズしてください。特にURLはesc_url()を使用してください。 - WordPress 5.0以降はGutenbergが標準エディタです。新規開発ではブロックの実装を優先し、ショートコードは後方互換性のために残す形が推奨されます。
まとめ
ショートコードは「add_shortcode()登録→shortcode_atts()でデフォルト値→属性サニタイズ→文字列をreturn」の流れで実装します。新規サイトではGutenbergブロックへの移行も検討しながら、既存コンテンツとの互換性を保ちましょう。関連記事:WordPressのfunctions.phpを安全に編集する方法、Gutenbergカスタムブロックを作成する方法。