JS variable loaded using wp_localize_script is no longer available

TL;DR: Call the wp_localize_script after registering/enqueuing the script you are localizing.

Recently (WP 4.1.4 / WP 4.2) my ajax scripts stopped working. I’ve noticed that it was caused by the fact that the variable for the ajax_url was undefined so for some reason it ws no longer loaded to the page.

The reason turned out to be that I was using wp_localize_script to load the ajax url variable for a script that was not yet registered and enqueued.

Seeing the codex now I noticed that they have added: “IMPORTANT! wp_localize_script() MUST be called after the script it’s being attached to has been registered using wp_register_script() or wp_enqueue_script()”. However I don’t remember this not working before and also it did work until now.

So mind to check every site you have made using WP ajax and following the good practices (to load the ajax url using wp_localize_scripts) if they are still working.

One Reply to “JS variable loaded using wp_localize_script is no longer available”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.