概要
wp_sanitize_script_attributesフィルタは、スクリプト要素の属性テキストを取得する際に使用されるフィルタです。このフィルタを利用することで、HTML内に出力されるスクリプトタグの属性を安全にサニタイズできます。主に次のような場面で使われます。
- スクリプトの信頼性を向上させるための属性の追加
- 不正な属性を除去するためのカスタマイズ
- HTML5の新しい属性への対応
- プラグインやテーマの互換性の維持
- セキュリティを強化するための属性チェック
- 開発者が独自の属性を追加するためのカスタマイズ
- 子テーマでの親テーマの属性の変更
- ライブラリのバージョン管理やCDNの利用
構文
apply_filters( 'wp_sanitize_script_attributes', $attributes, $tag );
パラメータ
$attributes: 調整される属性の配列$tag: スクリプトタグの名前
戻り値
- フィルタリングされた属性の配列
関連する関数
使用可能なバージョン
WordPress 4.8 以降で使用可能です。
コアファイルのパス
wp-includes/script-loader.php
この関数のアクションでの使用可能性
| アクション | 使用可能性 |
|---|---|
| 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 | 〇 |
サンプルコード
サンプルコード 1: 属性のサニタイズ
function my_custom_script_attributes( $attributes, $tag ) {
// 不正な属性を除去
unset( $attributes['onerror'] );
return $attributes;
}
add_filter( 'wp_sanitize_script_attributes', 'my_custom_script_attributes', 10, 2 );
このサンプルコードは、onerror属性をスクリプト要素から除去するフィルタを追加しています。
サンプルコード 2: 独自属性の追加
function add_custom_attribute( $attributes, $tag ) {
// 独自のデータ属性を追加
$attributes['data-custom'] = 'my-value';
return $attributes;
}
add_filter( 'wp_sanitize_script_attributes', 'add_custom_attribute', 10, 2 );
このコードは、スクリプト要素にカスタムのデータ属性data-customを追加する例です。
サンプルコード 3: セキュリティ向上のためのチェック
function secure_script_attributes( $attributes, $tag ) {
// 信頼できない属性を削除
if ( ! empty( $attributes['src'] ) && strpos( $attributes['src'], 'http://' ) === 0 ) {
unset( $attributes['src'] );
}
return $attributes;
}
add_filter( 'wp_sanitize_script_attributes', 'secure_script_attributes', 10, 2 );
このサンプルは、不正なhttpのソースを持つスクリプト要素をサニタイズします。
サンプルコード 4: HTML5属性の対応
function add_html5_attributes( $attributes, $tag ) {
if ( 'script' === $tag ) {
$attributes['defer'] = 'defer';
}
return $attributes;
}
add_filter( 'wp_sanitize_script_attributes', 'add_html5_attributes', 10, 2 );
このコードは、HTML5のdefer属性をスクリプト要素に追加する例です。
サンプルコード 5: 属性名のカスタマイズ
function customize_script_attribute_keys( $attributes, $tag ) {
if ( array_key_exists( 'async', $attributes ) ) {
$attributes['data-async'] = $attributes['async'];
unset( $attributes['async'] );
}
return $attributes;
}
add_filter( 'wp_sanitize_script_attributes', 'customize_script_attribute_keys', 10, 2 );
このサンプルは、async属性の名前をdata-asyncに変更します。