wp_localize_script() is used by many developers to pass data from PHP to JavaScript. However, wp_localize_script() is intended to be used for localization and internationalization. Developers are using this to pass random data to script because it works and it was originally the only official way to do that.
Now we have wp_add_inline_script() introduced since WordPress v4.5 and is now the best practice to use this function to pass random data from PHP to page scripts. It basically works the same way as wp_localize_script(), itβs just that the function name is more appropriate for the intended use.
Here’s the example and equivalent:
wp_localize_script()
wp_localize_script(
'script-handle',
'my_script_params',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'my_nonce' => wp_create_nonce( 'my_nonce' )
)
);
wp_add_inline_script() equivalent
wp_add_inline_script(
'script-handle',
'const my_script_params = ' . json_encode(
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'my_nonce' => wp_create_nonce( 'my_nonce' )
)
),
'before'
);
Both works only if the script has already been added.