shortcode_parse_atts()


関数WordPressshortcode_parse_atts()—は、ショートコードの属性を解析し、連想配列として返すために使用されます。

シンタックス

shortcode_parse_atts( string $text );

引数の説明:

  • $text (string) — 解析するショートコードの属性が含まれる文字列。

例 1: ショートコード属性を配列として取得

以下のコードは、ショートコードの属性を解析し、連想配列として返します。

<?php
$text = 'title="タイトル" id="123" class="クラス"';
$atts = shortcode_parse_atts($text);
print_r($atts);
?>

例 2: デフォルト値を設定して解析

このコードでは、デフォルト値を用意し、解析後にデフォルト値をマージします。

<?php
$text = 'id="123"';
$defaults = array(
    'title' => 'デフォルトタイトル',
    'id' => '',
    'class' => 'デフォルトクラス'
);
$atts = shortcode_parse_atts($text);
$atts = shortcode_atts($defaults, $atts);
print_r($atts);
?>

例 3: ショートコードを条件付きで解析

指定された属性が存在する場合にのみ処理を実行します。

<?php
$text = 'title="タイトル"';
$atts = shortcode_parse_atts($text);
if (isset($atts['title'])) {
    echo 'タイトルは: ' . $atts['title'];
}
?>

例 4: 動的属性解析

カスタムデータをショートコード属性として動的に解析します。

<?php
$text = 'title="動的タイトル" data-value="12345"';
$atts = shortcode_parse_atts($text);
foreach ($atts as $key => $value) {
    echo $key . ': ' . $value . '<br>';
}
?>

例 5: 関数の中でショートコード属性を使用

関数内で解析結果を使って動的な処理を行います。

<?php
function custom_shortcode_function($text) {
    $atts = shortcode_parse_atts($text);
    if (!empty($atts['title'])) {
        return 'タイトルは: ' . $atts['title'];
    }
    return 'タイトルがありません';
}
echo custom_shortcode_function('title="カスタムタイトル"');
?>

注意事項

  • shortcode_parse_atts()は適切なフォーマットの文字列でのみ正確に動作します。フォーマットが正しくない場合、予期しない結果になる可能性があります。
  • 不明な属性が含まれている場合、それらは解析されますが、用途に注意してください。

関連機能: