WordPress does some odd things when it comes to managing the DOM elements, especially when it comes to JavaScript and CSS. WordPress has crafted their own creative PHP methodology for getting data from PHP into JavaScript when loading the scripts. This allows for JavaScript variables to be “pre-initialized” when the scripts are first rendered.
Useful for getting a known starting state in JavaScript based on PHP state and logic that has run up to the point that the scripts are loaded.
Not standard AT ALL given today’s single page app and other advanced methodologies just as REST queries, etc. that could do the same job.
Localizing A Script
The original concept was to use the pre-loaded-from-PHP JavaScript variables to managed language translations. It was a hack to get JavaScript to be able to manage i18n/l10n issues without having to load a completely separate JavaScript localization module in addition to the WordPress-required PHP modules that did the same thing… thus the name “Localizing A Script”.
Today that “localize script” feature is used by many plugins, including SLP, to pre-initialized JavaScript variables with starting values.
There are several stages to getting the JavaScript loaded in a user’s browser with the pre-initialized values.
- Register the script (wp_register_script).
- Translate the PHP variables into JavaScript variables (wp_localize_script) using the CDATA mechanism.
- Enqueue the script (wp_enqueue_script).
Store Locator Plus® and Localized Admin Scripts
Many admin scripts rely on the wp_data JavaScript variable to be set in order to function.
This is managed in the SLP_BaseClass_Admin PHP file in the enqueue_admin_javascript() method.
post image from Pixabay: https://pixabay.com/photos/birds-branch-wild-birds-zonotrichia-7376432/