ワードプレスのwp_kses_allowed_htmlフィルタの使用方法・解説

概要

wp_kses_allowed_htmlフィルタは、WordPressが許可するHTMLタグと属性を取得するために使用されるフィルタです。このフィルタは、ユーザーが提供したコンテンツを安全に処理するために役立ちます。有効なHTMLタグ情報を取得するために、次のような機能を実装する際によく使われます:

  1. ユーザー入力の検証
  2. クリエイターが登録したカスタムポストタイプのコンテンツフィルタリング
  3. コメントや文章内のHTMLタグの制限
  4. プラグインが生成する出力をクリーンアップ
  5. ショートコードのサニタイズ
  6. ユーザー生成コンテンツの表示時の安全性確保
  7. 投稿およびページのエディタでのHTML制限
  8. カスタムメタボックスのHTMLフィルタリング

構文

wp_kses_allowed_html( $context );

パラメータ

  • $context (string): 取得するタグのコンテキスト。たとえば、’post’や’comment’など。

戻り値

  • (array): 指定されたコンテキストに応じた許可されたHTMLタグと属性の配列。

関連する関数

wp_kses_allowed_html

ワードプレスのバージョン

  • このフィルタは、WordPress 3.0.0以降で使用可能です。

コアファイルのパス

  • /wp-includes/kses.php

サンプルコード

サンプル1: 基本的な使用例

add_filter( 'wp_kses_allowed_html', 'my_custom_allowed_html', 10, 2 );

function my_custom_allowed_html( $allowed_html, $context ) {
    if ( 'post' === $context ) {
        $allowed_html['iframe'] = array(
            'src'            => array(),
            'width'          => array(),
            'height'         => array(),
            'frameborder'    => array(),
            'allowfullscreen' => array(),
        );
    }
    return $allowed_html;
}

このコードは、’post’コンテキストでiframeタグを許可するためのフィルタを追加します。

サンプル2: カスタム属性の追加

add_filter( 'wp_kses_allowed_html', 'custom_attributes_for_gallery', 10, 2 );

function custom_attributes_for_gallery( $allowed_html, $context ) {
    if ( 'post' === $context ) {
        $allowed_html['img']['data-attribute'] = array();
    }
    return $allowed_html;
}

このコードは、’post’コンテキストでimgタグに任意のカスタムデータ属性を追加する許可をします。

サンプル3: 特定のタグを制限

add_filter( 'wp_kses_allowed_html', 'limit_allowed_tags', 10, 2 );

function limit_allowed_tags( $allowed_html, $context ) {
    if ( 'comment' === $context ) {
        unset( $allowed_html['script'] );
        unset( $allowed_html['iframe'] );
    }
    return $allowed_html;
}

このコードは、コメントコンテキストでscriptとiframeタグを取り除きます。

サンプル4: 特定のコンテキストの調整

add_filter( 'wp_kses_allowed_html', 'adjust_allowed_html_for_specific_context', 10, 2 );

function adjust_allowed_html_for_specific_context( $allowed_html, $context ) {
    if ( 'post_excerpt' === $context ) {
        $allowed_html['strong'] = array();
    }
    return $allowed_html;
}

このコードは、post_excerptコンテキストでstrongタグを許可します。

サンプル5: 属性の制限設定

add_filter( 'wp_kses_allowed_html', 'restrict_image_attributes', 10, 2 );

function restrict_image_attributes( $allowed_html, $context ) {
    if ( 'post' === $context ) {
        $allowed_html['img'] = array(
            'src' => array(),
            'alt' => array(),
        );
    }
    return $allowed_html;
}

このコードは、’post’コンテキストでimgタグのsrcとalt属性のみを許可します。

この関数のアクションでの使用可能性

アクション 使用可能性
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

非推奨または削除されたバージョン

  • 特定のバージョンにおいて非推奨または削除された情報はありません。

この関数について質問する


上の計算式の答えを入力してください