WP_Scripts::localize
Localizes a script, only if the script has already been added.
Метод класса: WP_Scripts{}
Хуков нет.
Возвращает
true|false. True on success, false on failure.
Использование
global $wp_scripts; $wp_scripts->localize( $handle, $object_name, $l10n );
- $handle(строка) (обязательный)
- Name of the script to attach data to.
- $object_name(строка) (обязательный)
- Name of the variable that will contain the data.
- $l10n(массив) (обязательный)
- Array of data to localize.
Список изменений
| С версии 2.1.0 | Введена. |
Код WP_Scripts::localize() WP Scripts::localize WP 6.8.3
public function localize( $handle, $object_name, $l10n ) {
if ( 'jquery' === $handle ) {
$handle = 'jquery-core';
}
if ( is_array( $l10n ) && isset( $l10n['l10n_print_after'] ) ) { // back compat, preserve the code in 'l10n_print_after' if present.
$after = $l10n['l10n_print_after'];
unset( $l10n['l10n_print_after'] );
}
if ( ! is_array( $l10n ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: 1: $l10n, 2: wp_add_inline_script() */
__( 'The %1$s parameter must be an array. To pass arbitrary data to scripts, use the %2$s function instead.' ),
'<code>$l10n</code>',
'<code>wp_add_inline_script()</code>'
),
'5.7.0'
);
if ( false === $l10n ) {
// This should really not be needed, but is necessary for backward compatibility.
$l10n = array( $l10n );
}
}
if ( is_string( $l10n ) ) {
$l10n = html_entity_decode( $l10n, ENT_QUOTES, 'UTF-8' );
} elseif ( is_array( $l10n ) ) {
foreach ( $l10n as $key => $value ) {
if ( ! is_scalar( $value ) ) {
continue;
}
$l10n[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
}
}
$script = "var $object_name = " . wp_json_encode( $l10n ) . ';';
if ( ! empty( $after ) ) {
$script .= "\n$after;";
}
$data = $this->get_data( $handle, 'data' );
if ( ! empty( $data ) ) {
$script = "$data\n$script";
}
return $this->add_data( $handle, 'data', $script );
}