функция since 5.7.0

wp_get_inline_script_tag()

Проверено на WordPress 6.9, обновлено Источник: WordPress Developer Resources.

Сигнатура

wp_get_inline_script_tag( string $data, $attributes = array() ): string

Описание

В тег можно внедрить атрибуты с помощью фильтра ‘wp_inline_script_attributes’. Если $data небезопасно встраивать в тег , будет возвращён пустой тег script с указанными атрибутами. Содержимое JavaScript и JSON можно экранировать, поэтому проблема, скорее всего, возникнет только с необычными типами содержимого. Пример: // Опасный JavaScript в этом примере будет безопасно экранирован. // Будет возвращена строка с тегом script и нужным содержимым. wp_get_inline_script_tag( 'console.log( "" );' );

// Эти данные небезопасны, и `text/plain` нельзя экранировать.
// Следующий вызов вернёт `""` , указывая на неудачу:
wp_get_inline_script_tag( '', array( 'type' => 'text/plain' ) );

Оригинал (английский)

It is possible to inject attributes in the <script> tag via the ‘wp_inline_script_attributes’ filter.

If the $data is unsafe to embed in a <script> tag, an empty script tag with the provided attributes will be returned. JavaScript and JSON contents can be escaped, so this is only likely to be a problem with unusual content types.

Example:

// The dangerous JavaScript in this example will be safely escaped.
// A string with the script tag and the desired contents will be returned.
wp_get_inline_script_tag( 'console.log( "</script>" );' );

// This data is unsafe and `text/plain` cannot be escaped.
// The following will return `""` to indicate failure:
wp_get_inline_script_tag( '</script>', array( 'type' => 'text/plain' ) );

Параметры

$data string обязательный
Данные для тега script: JavaScript, importmap, speculationrules и т. д.

Возвращаемое значение

string

""

Исходный код

wp-includes/script-loader.php:3010

function wp_get_inline_script_tag( $data, $attributes = array() ) {
	$data = "\n" . trim( $data, "\n\r " ) . "\n";

	/**
	 * Filters attributes to be added to a script tag.
	 *
	 * @since 5.7.0
	 *
	 * @param array<string, string|bool> $attributes 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.
	 * @param string                     $data       Inline data.
	 */
	$attributes = apply_filters( 'wp_inline_script_attributes', $attributes, $data );

	$processor = new WP_HTML_Tag_Processor( '<script></script>' );
	$processor->next_tag();
	foreach ( $attributes as $name => $value ) {
		/*
		 * Lexical variations of an attribute name may represent the
		 * same attribute in HTML, therefore its possible that the
		 * input array might contain duplicate attributes even though
		 * its keyed on their name. Calling code should rewrite an
		 * attributes value rather than sending a duplicate attribute.
		 *
		 * Example:
		 *
		 *     array( 'id' => 'main', 'ID' => 'nav' )
		 *
		 * In this example, there are two keys both describing the `id`
		 * attribute. PHP array iteration is in key-insertion order so
		 * the 'id' value will be set in the SCRIPT tag.
		 */
		if ( null !== $processor->get_attribute( $name ) ) {
			continue;
		}

		$processor->set_attribute( $name, $value ?? true );
	}

	if ( ! $processor->set_modifiable_text( $data ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			__( 'Unable to set inline script data.' ),
			'7.0.0'
		);
		return '';
	}

	return "{$processor->get_updated_html()}\n";
}

История изменений

ВерсияОписание
7.0.0 Returns an empty string if the data cannot be safely embedded in a script tag.
5.7.0 Introduced.

Что будем искать? Например,Продвижение

Этот сайт использует куки-файлы. Оставаясь на сайте, Вы соглашаетесь на их использование. Для получения дополнительной информации, пожалуйста, ознакомьтесь с политикой в отношении персональных данных.