I have tried both wp_localize_script and wp_add_inline_script : it doesn’t work the way I expect.
I have this in my plugin’s PHP file (it is enqueued with wp_enqueue_scripts somewhere else but I don’t need to write the code here right ?) :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
false
);
wp_enqueue_script(
'custom-profile-script'
);
wp_localize_script(
'custom-profile-plugin',
'wp_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' ),
'plugin_url' => "url"
)
);
wp_add_inline_script( 'custom-profile-plugin', 'const PHPVAR = ' . json_encode( array(
'plugin_url' => "url"
) ), 'before' );
And then, in my js file :
var data = {
action: 'custom_user_plugin_update_meta_rating_value',
security: wp_ajax.ajaxnonce
};
$.post(wp_ajax.ajax_url, data, function(result) {
console.log(wp_ajax);
console.log(PHPVAR.plugin_url);
});
The first console log (related to wp_localize_script) is an object that contains "ajax_url" and "ajax_nonce" with the right values, but "plugin_url" doesn’t appear and is UNDEFINED when I call it using wp_ajax.plugin_url.
The second console log (related to wp_add_inline_script) tells me that PHPVAR is not defined…
What I don’t understand is why the first two values are passed correctly using localize script, but not the third one and, furthermore, why wp_add_inline_script doesn’t work.
2
Answers
The script needs to be registered in the footer for the PHP value to be passed, like this :
Instead of :
You need to add
wp_enqueue_script
afterwp_localize_script
and also you add wrong handle towp_localize_script
check the below code.