wp_localize_script()
now uses json_encode()
which means a multidimensional array will now work for the passed data. And, HTML entity decoding only applies to the first level of the array.
Better is an way to use json and default js possibilities from WP.
At first, i add the options from the database via script and json_encode
to wp header:
add_action( 'admin_enqueue_scripts', 'fb_print_scripts' );
function fb_print_scripts() {
global $current_screen;
if ( isset( $current_screen -> id ) && ! in_array( $current_screen -> id, array( 'post', 'page' ) ) )
return;
if ( is_plugin_active_for_network( plugin_basename( __FILE__ ) ) )
$options = get_site_option( 'my_options_id' );
else
$options = get_option( 'my_options_id' );
if ( ! $options )
return;
?>
<script type="text/javascript">
var my_json_object = <?php echo htmlspecialchars( json_encode( $options ) ); ?>;
</script>
<?php
}
after this i read this data via javascript; the script include via wp_enqueue_script
; the follow example init only in admin, you can change the hook without admin_
to include also in frontend.
add_action( 'admin_enqueue_scripts', 'fb_admin_enqueue_scripts' );
function fb_admin_enqueue_scripts( $where ) {
if ( ! in_array( $where, array( 'post.php', 'post-new.php', ) )
return;
$suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '.dev' : '';
wp_enqueue_script(
self :: get_textdomain() . '_script',
plugins_url( '/js/my_script' . $suffix. '.js', __FILE__ ),
array( 'jquery', 'my_other_script' ),
'',
TRUE
);
}
now you can use the data from json inside your script, example
jQuery( document ).ready( function( $ ) {
if ( typeof my_json_object == 'undefined' )
return;
// debug in console of Browser
console.dir( my_json_object );
});