wp_sanitize_script_attributes() WordPress Function

The wp_sanitize_script_attributes() function is used to clean up script attributes before they are added to the DOM. This is important for security and performance reasons. The function strips out invalid characters and ensures that the attribute values are properly encoded.

wp_sanitize_script_attributes( array $attributes ) #

Sanitizes an attributes array into an attributes string to be placed inside a tag.


Description

Automatically injects type attribute if needed. Used by wp_get_script_tag() and wp_get_inline_script_tag().


Top ↑

Parameters

$attributes

(array)(Required)Key-value pairs representing <script> tag attributes.


Top ↑

Return

(string) String made of sanitized <script> tag attributes.


Top ↑

Source

File: wp-includes/script-loader.php

function wp_sanitize_script_attributes( $attributes ) {
	$html5_script_support = ! is_admin() && ! current_theme_supports( 'html5', 'script' );
	$attributes_string    = '';

	// If HTML5 script tag is supported, only the attribute name is added
	// to $attributes_string for entries with a boolean value, and that are true.
	foreach ( $attributes as $attribute_name => $attribute_value ) {
		if ( is_bool( $attribute_value ) ) {
			if ( $attribute_value ) {
				$attributes_string .= $html5_script_support ? sprintf( ' %1$s="%2$s"', esc_attr( $attribute_name ), esc_attr( $attribute_name ) ) : ' ' . esc_attr( $attribute_name );
			}
		} else {
			$attributes_string .= sprintf( ' %1$s="%2$s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) );
		}
	}

	return $attributes_string;
}


Top ↑

Changelog

Changelog
VersionDescription
5.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.