shortcode_atts()


WordPress関数shortcode_atts()は、ショートコードのデフォルト属性を設定および上書きするために使用されます。この関数を使用することで、ショートコードをより柔軟に制御できます。

構文

shortcode_atts( array $pairs, array $atts, string $shortcode = '' );

引数の説明:

  • $pairs (array) — デフォルト値の連想配列。
  • $atts (array) — ショートコードで渡された属性。
  • $shortcode (string) — 使用するショートコード名(オプション)。

例 1: ショートコードの属性のマージ

以下のコードはデフォルト値とユーザー指定の属性をマージします。

<?php
$default_atts = array(
    'color' => 'red',
    'size' => 'medium',
);
$atts = shortcode_atts( $default_atts, $atts );
?>

例 2: ショートコードでの背景色設定

ショートコードで指定された背景色を取得し、デフォルトで「white」を設定します。

<?php
function my_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'bg_color' => 'white',
    ), $atts );
    return '<div style="background-color: ' . esc_attr( $atts['bg_color'] ) . ';">コンテンツ</div>';
}
add_shortcode( 'custom_box', 'my_shortcode' );
?>

例 3: デフォルトテキストを変更する

ユーザーが指定したテキストを優先し、デフォルト値を使用する例です。

<?php
function my_text_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'text' => 'デフォルトテキスト',
    ), $atts );
    return '<p>' . esc_html( $atts['text'] ) . '</p>';
}
add_shortcode( 'custom_text', 'my_text_shortcode' );
?>

例 4: ボタンショートコードのカスタマイズ

ボタンの色とテキストを設定するショートコード。

<?php
function button_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'color' => 'blue',
        'label' => 'クリック',
    ), $atts );
    return '<button style="color: ' . esc_attr( $atts['color'] ) . ';">' . esc_html( $atts['label'] ) . '</button>';
}
add_shortcode( 'custom_button', 'button_shortcode' );
?>

例 5: 画像サイズの設定

ショートコードを使用して画像サイズを指定します。

<?php
function image_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'width' => '300px',
        'height' => '200px',
    ), $atts );
    return '<img src="path/to/image.jpg" style="width: ' . esc_attr( $atts['width'] ) . '; height: ' . esc_attr( $atts['height'] ) . ';">';
}
add_shortcode( 'custom_image', 'image_shortcode' );
?>

注意事項

  • shortcode_atts()を使用するときは、ユーザー入力を適切にサニタイズする必要があります。
  • 属性のデフォルト値は、意味のある初期値に設定することをお勧めします。

関連機能: