ショートコードを使用するシナリオには2種類あります:
- ショートコードは、基本のショートコードのセクションで見たような、自己完結型のタグ。
- ショートコードは、コンテンツを囲むタグ。
囲まれたコンテンツ
ショートコードでコンテンツを囲むことで、囲まれたコンテンツに対する操作が可能になります。
[wporg]content to manipulate[/wporg]
上で見たように、コンテンツのセクションを囲むために必要なことは、HTML と同じように、始まりの [$tag]
と終わりの [/$tag]
を追加することです。
囲まれたコンテンツの処理
元のショートコード [wporg]
に戻りましょう:
function wporg_shortcode( $atts = array(), $content = null ) {
// do something to $content
// always return
return $content;
}
add_shortcode( 'wporg', 'wporg_shortcode' );
コールバック関数を見ると、$atts
と $content
の2つのパラメータを受け取るようにしたことがわかります。パラメータ $content
は、囲んだ内容を保持します。$atts
については後で説明します。
$content
のデフォルト値は null
に設定されているので、PHP 関数 is_null()
を使うことで、自己完結型タグと内包型タグを区別できます。
ショートコード [$tag]
は、その内容と末尾の [/$tag]
も含めて、ハンドラ関数の 戻り値 に置き換えられます。
入れ子状態のショートコード
ショートコード・パーサーは、投稿のコンテンツに対して シングルパス を実行します。
つまり、ショートコード・ハンドラの $content
パラメータに、別のショートコードが含まれている場合、そのショートコードは解析されません。この例では、[shortcode]
は、処理されません:
[wporg]another [shortcode] is included[/wporg]
ハンドラ関数の 最終戻り値 で do_shortcode()
を呼び出すことで、他のショートコードの中でショートコードを使用できます。
function wporg_shortcode( $atts = array(), $content = null ) {
// do something to $content
// run shortcode parser recursively
$content = do_shortcode( $content );
// always return
return $content;
}
add_shortcode( 'wporg', 'wporg_shortcode' );
制限事項
ショートコード・パーサーは、同じ [$tag]
を囲む形式と囲まない形式を混在させて扱うことができません。
[wporg] non-enclosed content [wporg]enclosed content[/wporg]
パーサーは、「non-enclosed content
」というテキストで区切られた2つのショートコードとして扱う代わりに、これを「non-enclosed content [wporg]enclosed content
」を囲む1つのショートコードとして扱います。