How To Use JS Path For Image In WordPress

Quick Summary

  • Pass the theme URL from PHP to JavaScript with wp_localize_script(), since JavaScript files can't call get_template_directory_uri() themselves.
  • Hooked to wp_enqueue_scripts, the code attaches a my_data object to the jquery handle, holding the theme folder URL for your scripts.
  • In a child theme, use get_stylesheet_directory_uri() for images stored there, and load your script after jQuery so my_data exists.

JavaScript files can’t run PHP, so they can’t call get_template_directory_uri() to find your theme’s folder, and a hardcoded URL breaks as soon as the site moves to another domain. The fix is to pass the theme URL from PHP to JavaScript with wp_localize_script(). The example uses it for the arrow images of an Owl Carousel slider in a WordPress theme.

Step 1: pass the theme URL to JavaScript

Add this code to your theme’s functions.php file.

PHP
//js variable
function theme_name_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','theme_name_set_js_var');

On the wp_enqueue_scripts hook, wp_localize_script() attaches a JavaScript object named my_data to the jquery script handle. WordPress prints it as an inline script on pages that load jQuery, and my_data.template_directory_uri holds the URL of your theme folder.

Step 2: use the path in your JavaScript

Then use the value in your JavaScript file wherever you need an image path. In this case it builds the previous and next buttons of an Owl Carousel slider:

Code
navText: ['<img src="' + my_data.template_directory_uri + '/assets/img/slider-left.png" alt="prev">', '<img src="' + my_data.template_directory_uri + '/assets/img/slider-right.png" alt="next">']

navText is the Owl Carousel option for the content of the navigation buttons. Each string builds an <img> tag from the theme URL plus the image’s path inside the theme, here /assets/img/. Add it to the options object you pass to owlCarousel(), together with nav: true so the buttons are shown.

  • In a child theme, get_template_directory_uri() returns the parent theme’s URL. Use get_stylesheet_directory_uri() if the images are in the child theme. The difference between the parent and child theme path functions is explained separately.
  • Your script has to load after jQuery (list jquery as a dependency when you enqueue it) so my_data exists when your code runs.
  • You can rename my_data to something more specific to your theme; just use the same name in PHP and JavaScript.
Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More