get_shortcode_regex()


WordPress関数get_shortcode_regex()は、ショートコードを解析するための正規表現パターンを生成する関数です。この関数を使用して、投稿やページのコンテンツ内でショートコードを検索または処理できます。

構文

get_shortcode_regex( array $tagnames = null );

引数の説明:

  • $tagnames (array) — 特定のショートコードタグの名前を配列で指定します。この引数が指定されていない場合、すべてのショートコードを対象とします。

例1. 全てのショートコードを検索する

以下のコードは、投稿内に含まれるすべてのショートコードを正規表現を使用して検索します。

<?php
$content = get_the_content();
$pattern = get_shortcode_regex();
preg_match_all( '/' . $pattern . '/', $content, $matches );
print_r( $matches );
?>

例2. 特定のショートコードを検索する

特定のショートコード(例: )を検索する場合の例です。

<?php
$content = get_the_content();
$pattern = get_shortcode_regex( array( 'gallery' ) );
preg_match_all( '/' . $pattern . '/', $content, $matches );
print_r( $matches );
?>

例3. ショートコードの属性を取得する

ショートコードの属性を解析して取得する例です。

<?php
$content = get_the_content();
$pattern = get_shortcode_regex( array( 'gallery' ) );
if ( preg_match( '/' . $pattern . '/', $content, $matches ) ) {
    $attributes = shortcode_parse_atts( $matches[3] );
    print_r( $attributes );
}
?>

例4. ショートコードを置換する

指定したショートコードを置換する例です。

<?php
$content = get_the_content();
$pattern = get_shortcode_regex( array( 'gallery' ) );
$content = preg_replace( '/' . $pattern . '/', '置換テキスト', $content );
echo $content;
?>

例5. カスタムショートコードの処理

カスタムショートコードを処理する例です。

<?php
add_shortcode( 'custom_shortcode', function( $atts, $content = null ) {
    return '<div>カスタムショートコードの出力: ' . $content . '</div>';
} );

$content = '[custom_shortcode]このテキストは処理されます[/custom_shortcode]';
$pattern = get_shortcode_regex( array( 'custom_shortcode' ) );
echo preg_replace_callback( '/' . $pattern . '/', function( $matches ) {
    return do_shortcode( $matches[0] );
}, $content );
?>

注意点

  • 正規表現を使用する際は、エスケープ漏れなどのセキュリティリスクに注意してください。
  • 大規模なコンテンツでの使用はパフォーマンスに影響を与える可能性があります。

関連機能: