0

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.

1

The way wp_localize_script() is supposed to be used is for that 2nd argument to be your namespace. Then you put an array as the 3rd argument for the values:

wp_localize_script(
    'my-script', 
    'namespace_name',
    array(
        'var_name' => $var,
    )
);

Now you can access the variable in the script with namespace_name.var_name.

If you also use the namespace in your script, instead of initialising the object, retrieve the object created by WordPress (or fall back to a new object if it's missing) and add to it:

var namespace_name = window.namespace_name || {};
namespace_name.new_var = 'Hello world!';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.