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

  • 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' ) )); – user1706680 Jan 21 '13 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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