How to localized one js file for different actions?

I have a group of javascript functions in one js file. each function acts on a specific action and get its own ajax response. some are on different pages, some are on the same page. If I don’t do the localize, I can’t get response. How can I localize this file for multi actions?

1 Answer
1

Maybe I got your question wrong. I don’t get what you mean by:

If I don’t do the localize, I can’t get response.

But in general, this function lets you localize your JS strings, but you can also use it to set JS variables:

function set_my_js_var() {
    // logic here for setting the right JS var
    return "some value";
}
function load_fe_scripts() {
    wp_enqueue_script( 'global-js-var', get_template_directory_uri() . '/js/my_file.js' );
    $localize_array = array(
        'my_js_var' => set_my_js_var()
    );
    wp_localize_script( 'global-js-var', 'my_global', $localize_array );
}
add_action('wp_enqueue_scripts', 'load_fe_scripts');

You can now acces the var in you JS File by my_global.my_js_var

Leave a Comment