How to get the path to current theme, but from a JS file?

I made a child theme from the default twentyseventeen theme. I’m loading a javascript file on functions.php using:

wp_enqueue_script(‘testpage’, get_stylesheet_directory_uri() . ‘/js/testscript.js’, array(‘jquery’), ”, true);

Then on that javascript file I’m trying to use load a .json using jQuery.getJSON. The .json file is in the same directory as the .js file. Since I enqueued the script using get_stylesheet_directory_uri(), I assumed the current path from that .js would be the path it’s located inside the theme? But apparently that’s not the case. If I try to to load the .json using a relative path to the same directory, then I get a 404.

jQuery.getJSON(“mydata.json”) will 404 because it’s actually looking at www.mysite.com/js/mydata.json and not at www.mysite.com/wp-content/themes/twentyseventeen-child/js/mydata.json

So I fixed it by just using jQuery.getJSON(“/wp-content/themes/twentyseventeen-child/js/mydata.json”) This works fine, currently.

But I’m afraid that doing so isn’t good practice? Hard coding the whole theme path like that in the JS file is bad, because that directory can change depending on installation, right? So is there some way to get the current theme path? Similar to get_stylesheet_directory_uri() in PHP? Or maybe there’s some other way entirely of doing this that would avoid this problem? Or is this no problem at all and I can just keep it like that?

Read more here:: How to get the path to current theme, but from a JS file?

Leave a Reply

Your email address will not be published. Required fields are marked *