wpseek.com
A WordPress-centric search engine for devs and theme authors



wp_add_crossorigin_attributes › WordPress Function

Since7.1.0
Deprecatedn/a
wp_add_crossorigin_attributes ( $html )
Parameters:
  • (string) $html HTML input.
    Required: Yes
Returns:
  • (string) Modified HTML.
Defined at:
Codex:

Adds crossorigin="anonymous" to relevant tags in the given HTML string.



Source

function wp_add_crossorigin_attributes( string $html ): string {
	$site_url = site_url();

	$processor = new WP_HTML_Tag_Processor( $html );

	// See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin.
	$cross_origin_tag_attributes = array(
		'AUDIO'  => array( 'src' ),
		'LINK'   => array( 'href' ),
		'SCRIPT' => array( 'src' ),
		'VIDEO'  => array( 'src', 'poster' ),
		'SOURCE' => array( 'src' ),
	);

	while ( $processor->next_tag() ) {
		$tag = $processor->get_tag();

		if ( ! isset( $cross_origin_tag_attributes[ $tag ] ) ) {
			continue;
		}
		$crossorigin = $processor->get_attribute( 'crossorigin' );
		if ( null !== $crossorigin ) {
			continue;
		}

		if ( 'AUDIO' === $tag || 'VIDEO' === $tag ) {
			$processor->set_bookmark( 'audio-video-parent' );
		}

		$processor->set_bookmark( 'resume' );

		$sought = false;

		$is_cross_origin = false;

		foreach ( $cross_origin_tag_attributes[ $tag ] as $attr ) {
			$url = $processor->get_attribute( $attr );
			if ( is_string( $url ) && ! str_starts_with( $url, $site_url ) && ! str_starts_with( $url, '/' ) ) {
				$is_cross_origin = true;
			}

			if ( $is_cross_origin ) {
				break;
			}
		}

		if ( $is_cross_origin ) {
			if ( 'SOURCE' === $tag ) {
				$sought = $processor->seek( 'audio-video-parent' );

				if ( $sought ) {
					$processor->set_attribute( 'crossorigin', 'anonymous' );
				}
			} else {
				$processor->set_attribute( 'crossorigin', 'anonymous' );
			}

			if ( $sought ) {
				$processor->seek( 'resume' );
				$processor->release_bookmark( 'audio-video-parent' );
			}
		}
	}

	return $processor->get_updated_html();
}