DocumentationInternationalizationJavaScript Localization

Javascript Localization

This document explains JavaScript localization in WP Bones. It covers using the wp_localize_script() function to pass localized strings from PHP to JavaScript. It suggests using wp_localize_script() for localized strings and wp_add_inline_script() for other data. In WP Bones, the withLocalizeScript() method is used to pass localized strings to JavaScript files. An example demonstrates how to pass localized strings and use them in a JavaScript file.



Overview

WordPress provides the wp_localize_script() function to pass data from PHP to JavaScript. This function is used to pass the localized strings to the JavaScript file.

More generally, the function wp_localize_script() is used to add a global JavaScript object with data. This function is often used to pass any type of data to JavaScript, not just localized strings. Today, it is possible to use wp_add_inline_script() to pass data to JavaScript. Our suggestion is to use wp_localize_script() only for passing localized strings.

So you should follow the same rule in WP Bones and use the fluent method withLocalizeScript() to pass the localized strings to the JavaScript file. And use the fluent withInlineScript() method to pass any other type of data to the JavaScript file.

Basic usage

In WP Bones you can use the fluent withLocalizeScript() method to pass the localized strings to the JavaScript file.

Here is an example of how to pass the localized strings to the JavaScript file:

Your Controller
$localization_data = array(
    'greeting' => __('Hello, World!', 'wp-kirk'),
    'farewell' => __('Goodbye, World!', 'wp-kirk'),
    'ajax_url' => admin_url('admin-ajax.php'),
);
 
return WPKirk()->view( 'dashboard.index' )
               ->with( [ 'kirk' => 'Captain' ] )
               ->withAdminScript( 'wp-kirk-common' )
               ->withLocalizeScript('wp-kirk-common', 'wpKirkGlobal', $localization_data);
wp-kirk-common.js
(function($) {
  'use strict';
  
  alert(wpKirkGlobal.greeting);
 
})(jQuery);