problems with wp_localize_script ?

Have you ever been in these situations where you consume hours or a whole day trying to find what the hell is wrong with your code? 

Why the stupid things doesn’t do what it is supposed to do?

  • Have i found a bug?
  • I am sure it is something silly..
  • and your useful time flies…

I am sure if you are a coder/developer this happens to you too.

Any way, to the point, i spent the whole afternoon trying to find out why the hell wp_localize_script() doesn’t echo it’s stuff in my source html.

I was calling it from within a function inside one of my template files. That’s the catch. As usual i started googling about problems with wp_localize_script, and most of the results were pointing out that you should call it after the relative wp_enqueue_script function (as i was doing) and before wp_footer();. So i was.

 

So what was the problem?

I am sure to some people this is obvious, but since i have already lost 5 hours trying to figure it out, debugging wordpress line by line, i can spent another 10 minutes writing about it.

So what i was actually doing was: i was calling wp_localize_script after wp_enqueue_script, but also after wp_head(), so the only way it would print out its stuff, was on wp_footer(). But the script-handler in my wp_enqueue_script referred to a script loaded in the <head> (see where this is going?). So all i had to do is use wp_localize… in conjunction with a script that is loaded in the footer of the page.

If i am wrong please leave a comment and let me know, but i haven’t seen written somewhere that wp_localize_script outputs it’s data in that way.

Well, i guess it’s should be obvious to me..

1 reply
  1. kse
    kse says:

    and i reply to myself:

    from the codex:
    “Furthermore, the actual output of the JavaScript script tag containing your localization variable occurs at the time that the enqueued script is printed (output/included on the page). This has some significant repercussions if you enqueue your script as you should using the appropriate actions (wp_enqueue_scripts and admin_enqueue_scripts), but wish to localize later using data that is not available at enqueue time.”

    so yeah. i am blind.

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">