_acf_kses_allowed_html()


WordPressの_acf_kses_allowed_html()関数は、ACF(Advanced Custom Fields)プラグインで使用される関数で、許可されたHTMLタグと属性をフィルタリングするために利用されます。この関数は、セキュリティを強化するために、ユーザー入力に対して特定のHTMLタグと属性のみを許可します。

構文

_acf_kses_allowed_html( array $allowed_html, string $context );

引数の説明:

  • $allowed_html (array) — 許可されるHTMLタグと属性の配列。
  • $context (string) — フィルタリングのコンテキスト。例えば、’acf’や’post’など。

例1: 基本的な使用例

ACFフィールドで許可されるHTMLタグと属性をカスタマイズする例です。

add_filter( 'acf_kses_allowed_html', 'custom_acf_kses_allowed_html', 10, 2 ); function custom_acf_kses_allowed_html( $allowed_html, $context ) { if ( $context === 'acf' ) { $allowed_html['a'] = array( 'href' => true, 'title' => true, 'target' => true ); } return $allowed_html; }

例2: 特定のコンテキストでのフィルタリング

特定のコンテキストでのみHTMLタグを許可する例です。

add_filter( 'acf_kses_allowed_html', 'custom_acf_kses_allowed_html', 10, 2 ); function custom_acf_kses_allowed_html( $allowed_html, $context ) { if ( $context === 'post' ) { $allowed_html['img'] = array( 'src' => true, 'alt' => true ); } return $allowed_html; }

例3: 複数のHTMLタグを許可

複数のHTMLタグと属性を一度に許可する例です。

add_filter( 'acf_kses_allowed_html', 'custom_acf_kses_allowed_html', 10, 2 ); function custom_acf_kses_allowed_html( $allowed_html, $context ) { if ( $context === 'acf' ) { $allowed_html['div'] = array( 'class' => true, 'id' => true ); $allowed_html['span'] = array( 'style' => true ); } return $allowed_html; }

例4: 特定の属性を削除

特定の属性を許可しないようにする例です。

add_filter( 'acf_kses_allowed_html', 'custom_acf_kses_allowed_html', 10, 2 ); function custom_acf_kses_allowed_html( $allowed_html, $context ) { if ( $context === 'acf' ) { unset( $allowed_html['a']['target'] ); } return $allowed_html; }

例5: カスタムコンテキストの追加

新しいカスタムコンテキストを追加して、それに応じてHTMLタグを許可する例です。

add_filter( 'acf_kses_allowed_html', 'custom_acf_kses_allowed_html', 10, 2 ); function custom_acf_kses_allowed_html( $allowed_html, $context ) { if ( $context === 'custom_context' ) { $allowed_html['iframe'] = array( 'src' => true, 'width' => true, 'height' => true ); } return $allowed_html; }

注意点

  • この関数を使用する際は、セキュリティを考慮して、必要なHTMLタグと属性のみを許可するようにしてください。
  • 許可するHTMLタグや属性を過度に増やすと、XSS(クロスサイトスクリプティング)のリスクが高まる可能性があります。