Best Practices for Passing PHP Data to JavaScript: A Comparison of wp_localize_script
and wp_add_inline_script
Storing data within static strings in your PHP files is a recommended practice. If this data is needed in your JavaScript code, incorporating it directly into your HTML using wp_localize_script
or wp_add_inline_script
is the best approach.
The traditional method involved using wp_enqueue_scripts
. Let's examine its successor, wp_localize_script
, and the newer, preferred method, wp_add_inline_script
.
wp_localize_script
Function
This function offers a structured way to pass data to your JavaScript. Here's its syntax:
wp_localize_script( $handle, $objectName, $arrayOfValues );
$handle
: The registered handle of your JavaScript file (e.g., 'my_js_library').$objectName
: The name of the JavaScript object that will contain your data.$arrayOfValues
: An associative array holding the data to pass.Example implementation within your functions.php
:
wp_enqueue_script( 'my_js_library', get_template_directory_uri() . '/js/myLibrary.js' ); $dataToBePassed = array( 'home' => get_stylesheet_directory_uri(), 'pleaseWaitLabel' => __( 'Please wait...', 'default' ) ); wp_localize_script( 'my_js_library', 'php_vars', $dataToBePassed );
In your JavaScript (myLibrary.js
), access the data like this: php_vars.home
and php_vars.pleaseWaitLabel
. This method eliminates the need for code within header.php
.
wp_add_inline_script
Function
This more recent function provides a streamlined approach. Its syntax is:
wp_add_inline_script( $handle, $data, $position = 'after' );
$handle
: The registered handle of your JavaScript file.$data
: A string containing the JavaScript code to be added. This should include the data you want to pass.$position
: Specifies where to add the inline script ('before' or 'after' the script).Example in your functions.php
:
wp_enqueue_script( 'my_js_library', get_template_directory_uri() . '/js/myLibrary.js' ); $dataToBePassed = array( 'home' => get_stylesheet_directory_uri(), 'pleaseWaitLabel' => __( 'Please wait...', 'default' ) ); wp_add_inline_script( 'my_js_library', 'const php_vars = ' . json_encode( $dataToBePassed ), 'before' );
Your JavaScript can access the data via php_vars.home
and php_vars.pleaseWaitLabel
. This method simplifies your code and keeps header.php
cleaner.
Conclusion
wp_add_inline_script
is generally preferred for its simplicity and efficiency. However, wp_localize_script
remains a valid option, particularly if you prefer a more structured approach to managing your data. Choose the method that best suits your coding style and project needs. This improved clarity and efficiency make these functions valuable tools for any WordPress developer.
The above is the detailed content of How to Pass PHP Data and Strings to JavaScript in WordPress. For more information, please follow other related articles on the PHP Chinese website!