wordpress localize script code example

Example 1: wp_localize_script

<?php
function pw_load_scripts() {
 
	wp_enqueue_script('pw-script', plugin_dir_url( __FILE__ ) . 'js/pw-script.js');
	wp_localize_script('pw-script', 'pw_script_vars', array(
			'alert' => __('Hey! You have clicked the button!', 'pippin')
		)
	);
 
}
add_action('wp_enqueue_scripts', 'pw_load_scripts');

Example 2: wordpress javascript localization

// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
 
// Localize the script with new data
$translation_array = array(
    'some_string' => __( 'Some string to translate', 'plugin-domain' ),
    'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );
 
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );

Tags:

Php Example