0

I’d like to know how to use the get_bloginfo( 'template_directory' ) tag in an external JS file.

I just found out that it’s possible using the wp_localize_script function but I didn’t manage to get it to work …

functions.php

wp_enqueue_script( 'custom_js' );
wp_localize_script('custom_js', 'wp_urls', array( 'template_dir' => get_bloginfo( 'template_directory' ) )); 

header.php (beneath wp_head();)

<script>
    alert(wp_urls.template_dir);
</script>   
7
  • Maybe changing to 'wp_urls' might work?
    – akTed
    Jan 21, 2013 at 14:46
  • I changed every hyphen to an underscore—but it still doesn’t work. Jan 21, 2013 at 14:59
  • 3
    Is the .js referenced by 'custom_js' loading in the <head>?
    – akTed
    Jan 21, 2013 at 15:03
  • 3
    ... and is it loading in the <head> before the alert?
    – s_ha_dum
    Jan 21, 2013 at 15:18
  • wp-head(); is called before the alert but there’s nothing added in the header by wp-head();. Jan 21, 2013 at 16:06

1 Answer 1

1

It doesn't work because you haven't enqueued your script properly. If the script isn't printed, neither are the variables set by wp_localize_script. Please read a WP Codex entry on wp_localize_script function. You have to include a path to the script after the handle.

1
  • Yep, I manage to get it to work with wp_enqueue_script( 'custom_js', get_bloginfo( 'template_directory' ) . '/js/google-map.js' ); wp_localize_script('custom_js', 'wp_urls', array( 'template_dir' => get_bloginfo( 'template_directory' ) )); Jan 21, 2013 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.