wp_localized_script is not defined when called via jquey ajax

To successfully add variable to the window object via wp_localize_script you need to properly invoke three functions in the following sequence:

  1. wp_register_script

  2. wp_localize_script

  3. wp_enqueue_script

In your case you’re missing the wp_register_script. In case someone experiences the same issue, follow the code procedures below.

PHP

<?php
    function my_theme_wp_enqueue_scripts() {
        $handle="my_handle";

        // Register the script
        wp_register_script($handle, '/path/to/my_script.js');

        // Localize the script with a new data
        wp_localize_script($handle, 'object_name', [
            'ajax_url' => admin_url('admin-ajax.php')
        ]);

        // Enqueue the script
        wp_enqueeu_script($handle);
    }
    add_action('wp_enqueue_scripts', 'my_theme_wp_enqueue_scripts');

Then, you can access the localized object in Javascript

var ajax_url = object_name.ajax_url;
console.log(ajax_url);

Change the $handle variable content as well as the object_name in PHP that makes sense to your application.

Leave a Comment