Hey everyone, I’m having trouble with image paths in my WordPress theme’s JavaScript file. I’ve set up a custom script using wp_enqueue_script()
, but the image references aren’t working since I switched to pretty permalinks.
My folder structure is simple:
themename/
├── js/
└── images/
In my functions.js
, I’m trying to set a background image like this:
myElement.style.background = "url('../images/icon-clear.png') no-repeat center";
I’ve tried different relative paths (../images
, ./images
, /images
) but nothing seems to work. I’d rather not use absolute paths if possible.
Is there a WordPress-friendly way to handle image paths in JS files? Maybe I’m missing something obvious, but I’m stumped. Any help would be awesome!
I’ve faced this issue before, and the solution that worked for me was using WordPress’s built-in wp_localize_script()
function. Here’s what you can do:
In your theme’s functions.php, after enqueuing your script, add:
wp_localize_script('your-script-handle', 'themeData', array(
'themeUrl' => get_template_directory_uri()
));
Then in your JavaScript file, you can access the image path like this:
myElement.style.background = `url('${themeData.themeUrl}/images/icon-clear.png') no-repeat center`;
This method ensures your paths are always correct, regardless of permalinks or directory structure changes. It’s also more maintainable in the long run.
hey mate, have u tried using wp_enqueue_script with the ‘in_footer’ parameter set to true? That way ur JS loads after WordPress stuff is ready. Then u can use wp.template() to grab image URLs from PHP. It’s a bit tricky but works like a charm once u get it goin!