Wp_localize_script not working in Sage 9?

You’ve only posted a small snippet of your code, but based on some experimentation with a clean Sage install, my guess is that you’re not putting these function calls inside of an appropriate action. In app/setup.php, the original call to wp_enqueue_script() is wrapped in an add_action() call to wp_enqueue_scripts. When the code you posted is put inside that call, it appears to work correctly:

// app/setup.php
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
    $ajax_params = array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'ajax_nonce' => wp_create_nonce('my_nonce'),
    );

    wp_localize_script('sage/main.js', 'ajax_object', $ajax_params);
}, 100);
// resources/assets/scripts/routes/common.js
export default {
  init() {
    // eslint-disable-next-line no-undef
    console.log(ajax_object);
  },
  finalize() {},
};

(Without the line // eslint-disable-next-line no-undef, yarn build will throw an error when you try to compile your JS.)

// browser console
Object { ajax_url: "http://sand.box/wp-admin/admin-ajax.php", ajax_nonce: "1a1b086c5c" }

Just running wp_enqueue_script/style on its own has no effect: It needs to be hooked to an action so it’s run at the appropriate time. wp_enqueue_scripts is generally a good hook to grab onto for that purpose.

13 Likes