Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

wordpress theme - set full img path in JS

Hello, I am trying to set the full theme path for an image inside my JS file. I've created a function in my functions.php:

  function set_js_var() {
       $translation_array = array( 'template_directory_uri' => get_template_directory_uri());
       wp_localize_script( 'jquery', 'my_data', $translation_array );
  } 
  add_action('wp_enqueue_scripts','set_js_var');  

// Inside my .js file I am calling the function with a variable:

    var image = '"'+ my_data.template_directory_uri+'/images/mai.png"';  

// And I use this variable later on in my document. The problem is when I preview the page in the browser
// then the image URL that shown in the source is:

 http://mywptheme/%22http:/mywptheme/wp-content/themes/mytheme/images/mai.png%22     

// I know I am calling the image inside my .js file but what the right path method should i use then?

2 Answers

ok since no one could answer my question here - this is the answer:

in .js file the var image was defined wrong:

var image = my_data.template_directory_uri+'/images/mai.png';
this is the right way and it works

David Klotz
David Klotz
19,659 Points

I've been looking for this forever! Thank you so much for posting!

ok since no one could answer my question here - this is the answer:

in .js file the var image was defined wrong:

var image = my_data.template_directory_uri+'/images/mai.png';
this is the right way and it works