strip_shortcodes()


WordPressのstrip_shortcodes()関数は、指定されたテキストからすべてのショートコードを削除するために使用されます。この関数は、コンテンツ内のショートコードを一時的に無効にしたり、ショートコードを含まないプレーンテキストを取得したりする場合に役立ちます。

構文

strip_shortcodes( string $content );
  • $content(string) — ショートコードを削除したいテキスト内容。

例1: 基本的な使用例

この例では、投稿のコンテンツからショートコードを削除します。

<?php echo strip_shortcodes(get_the_content()); ?>

例2: カスタムテキストからショートコードを削除

カスタムテキスト内のショートコードを削除する例です。

<?php echo strip_shortcodes('[gallery ids="1,2,3"]このテキストにはショートコードが含まれています。[/gallery]'); ?>

例3: ループ内での使用

ループ内で各投稿のコンテンツからショートコードを削除します。

<?php if (have_posts()) : while (have_posts()) : the_post(); echo strip_shortcodes(get_the_content()); endwhile; endif; ?>

例4: ショートコードを含むカスタムフィールドの処理

カスタムフィールドの値からショートコードを削除します。

<?php echo strip_shortcodes(get_post_meta(get_the_ID(), 'custom_field_key', true)); ?>

例5: ショートコードを削除したテキストを変数に保存

ショートコードを削除したテキストを変数に保存し、後で使用します。

<?php $clean_content = strip_shortcodes(get_the_content()); echo $clean_content; ?>

例6: 特定の投稿タイプでの使用

特定の投稿タイプ(例: ‘product’)のコンテンツからショートコードを削除します。

<?php $args = array('post_type' => 'product'); $query = new WP_Query($args); while ($query->have_posts()) : $query->the_post(); echo strip_shortcodes(get_the_content()); endwhile; wp_reset_postdata(); ?>

例7: ショートコードを削除してエクセプトを作成

ショートコードを削除したテキストを使用して、投稿のエクセプトを作成します。

<?php $excerpt = strip_shortcodes(get_the_content()); echo wp_trim_words($excerpt, 20); ?>

例8: 複数のショートコードを含むテキストの処理

複数のショートコードを含むテキストからすべてのショートコードを削除します。

<?php echo strip_shortcodes('[gallery ids="1,2,3"][audio src="example.mp3"][video src="example.mp4"]このテキストには複数のショートコードが含まれています。'); ?>

注意点

  • strip_shortcodes()は、ショートコードの処理を行わずに単純に削除します。ショートコードの結果を取得したい場合は、do_shortcode()を使用してください。
  • この関数は、テキスト内のすべてのショートコードを削除するため、特定のショートコードのみを削除したい場合は、正規表現を使用する必要があります。

関連機能: