As you are aware, wp_localize_script()
allows the creation of a JavaScript object from a PHP object.
So, after running the code in the example below:
wp_localize_script('my-script', 'var_name', $var); // This works
We will end with a JavaScript variable named var_name
that is accessible in the script my-script
. This JavaScript variable is copied from the original PHP variable $var
.
Everything is OK so far. The issue I am facing is this: I like to be able to assign var_name
to a JavaScript namespace; so in the following example, inside the object namespace_name
wp_localize_script('my-script', 'namespace_name.var_name', $var); // This does not work
But I am unable to do that, and wp_localize_script()
throws the following error in the web console: SyntaxError: unexpected token: '.'
Is there a way that I enable the use of wp_localize_script()
with JavaScript namespaces?
Note: I am passing a name space, as I like to keep all my JavaScript data within one object, to prevent naming conflicts and reduce clutter.