Question

I am enqueuing the script.js via a plugin succesfully but the wp_localize_script is not working and returning false. I have no clue why...

object_name is unavailable in the script.js when I remove the var_dump

function my_enqueue() {
  wp_enqueue_script( 'ajax-script', plugins_url( '/script.js', __FILE__ ), array('jquery') );
  var_dump(wp_localize_script( 'ajax_script', 'object_name', array( 'foo' => 'bar' ) ));
}

add_action( 'wp_enqueue_scripts', 'my_enqueue' );
Was it helpful?

Solution

Handle name doesn't match registered script name in your snippet.

wp_enqueue_script has ajax-script and localize has ajax_script notice the dash and underscore.

You should also follow example from the docs a. register, b. localise, c. enqueue; like so:

<?php

// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );

// Localize the script with new data
$translation_array = array(
    'some_string' => __( 'Some string to translate', 'plugin-domain' ),
    'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );

// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top