apply_filters( ‘wp_script_attributes’, array $attributes )

Filters attributes to be added to a script tag.

Parameters

$attributesarray
Key-value pairs representing <script> tag attributes.
Only the attribute name is added to the <script> tag for entries with a boolean value, and that are true.

Source

$attributes = apply_filters( 'wp_script_attributes', $attributes );

Changelog

VersionDescription
5.7.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    If you want to harden your website against supply chain attacks, you can use this filter to add Subresource integrity checking to a script.

    For example, for Select2 script at v4.0.9 from cdnjs.com, you would copy the SRI hash from https://cdnjs.com/libraries/select2/4.0.9, and add it as an attribute to the script.

    Then check for the select2-js ID, and that it is delivered by CDNJS, before adding the SRI attributes.

    /**
     * Add Subresource Integrity check to CDNJS Select2 script.
     *
     * @param  array $attr Attributes of each script.
     *
     * @return array $attr Attributes of each script.
     */
    function wpdocs_script_subresource_integrity( array $attr ): array {
    	if ( empty( $attr['id'] ) || empty( $attr['src'] ) ) {
    		return $attr;
    	}
    
    	if ( 'select2-js' === $attr['id'] && str_contains( $attr['src'], 'cdnjs.cloudflare.com' ) ) {
    		$attr['integrity']   = 'sha512-9p/L4acAjbjIaaGXmZf0Q2bV42HetlCLbv8EP0z3rLbQED2TAFUlDvAezy7kumYqg5T8jHtDdlm1fgIsr5QzKg==';
    		$attr['crossorigin'] = 'anonymous';
    	}
    
    	return $attr;
    }
    add_filter( 'wp_script_attributes', 'wpdocs_script_subresource_integrity', 10, 1 );

You must log in before being able to contribute a note or feedback.