概要
strip_shortcodes
フィルタは、投稿やページコンテンツからショートコードを取り除くための機能を提供します。このフィルタは、WordPressのテーマやプラグインの開発者が、ショートコードを処理する際に便利です。具体的には、一般的に以下のような場面で使用されます。
- ショートコードを含むコンテンツをプレーンテキストとして表示する必要がある場合。
- 特定の条件下でショートコードを無効にしたい場合。
- HTMLを出力する際に、無効なショートコードを取り除きたい場合。
- ショートコードの結果をキャッシュする前処理を行う場合。
- ショートコードが含まれない、シンプルな内容に変えたい場合。
- データベースからの検索結果を表示する場合にショートコードを排除するため。
- ユーザーの主張に対してフィルタを適用したい場合。
- テスト環境でショートコードを意図的に無効にするため。
構文
apply_filters( 'strip_shortcodes', $content );
パラメータ
$content
(string): ショートコードが含まれるコンテンツ。
戻り値
(string) ショートコードを取り除いた後のコンテンツ。
関連する関数
使用可能なバージョン
このフィルタは、WordPress 2.0以降で使用可能です。
コアファイルのパス
wp-includes/shortcodes.php
サンプルコード
サンプル1: ショートコードをプレーンテキストに変換
add_filter('the_content', 'remove_shortcodes_from_content');
function remove_shortcodes_from_content($content) {
return apply_filters('strip_shortcodes', $content);
}
このコードは、投稿やページのコンテンツからショートコードを取り除き、プレーンテキストとして表示させます。
サンプル2: 指定したショートコードのみ排除
add_filter('the_content', 'custom_strip_specific_shortcodes');
function custom_strip_specific_shortcodes($content) {
$content = str_replace('[my_shortcode]', '', $content);
return apply_filters('strip_shortcodes', $content);
}
このコードでは、特定のショートコード(例: [my_shortcode]
)を取り除き、他のショートコードはそのまま残します。
サンプル3: ショートコードからHTMLを取り除く
add_filter('the_content', 'remove_html_from_shortcodes');
function remove_html_from_shortcodes($content) {
$content = strip_tags($content);
return apply_filters('strip_shortcodes', $content);
}
このコードは、ショートコードを含むコンテンツからHTMLタグを取り除き、プレーンなテキストとして表示します。
サンプル4: ショートコードのキャッシュ用
add_action('wp_ajax_my_ajax_action', 'handle_ajax_request');
function handle_ajax_request() {
$content = $_POST['content'];
$stripped_content = apply_filters('strip_shortcodes', $content);
// 追加処理...
wp_send_json_success($stripped_content);
}
このコードスニペットは、AJAXリクエストを処理する際に、コンテンツからショートコードを取り除くために使用します。
サンプル5: ショートコードの無効化
remove_shortcode('gallery');
add_filter('the_content', 'disable_gallery_shortcode');
function disable_gallery_shortcode($content) {
return apply_filters('strip_shortcodes', $content);
}
このコードは、ギャラリーショートコードを削除し、投稿やページからそのショートコードを取り除きます。
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
mu_plugin_loaded | 〇 |
registered_post_type | 〇 |
plugins_loaded | 〇 |
wp_roles_init | 〇 |
setup_theme | 〇 |
after_setup_theme | 〇 |
set_current_user | 〇 |
init | 〇 |
register_sidebar | 〇 |
wp_loaded | 〇 |
send_headers | 〇 |
parse_query | 〇 |
pre_get_posts | |
wp | 〇 |
template_redirect | 〇 |
get_header | 〇 |
wp_head | 〇 |
非推奨又は削除されたバージョン
特に非推奨または削除されたバージョンはありません。