5

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?

8

You can use wp_localize_script to pass an object with the url to load before the file. and then in the file you can use it like testpage_obj.json_data

wp_register_script('testpage', get_stylesheet_directory_uri() . '/js/testscript.js', array('jquery'), '', true);
wp_localize_script( 'testpage', 'testpage_obj', array(
    'json_data' => get_stylesheet_directory_uri() . '/js/mydata.json'
) );
wp_enqueue_script('testpage');

In the JS file

jQuery.getJSON(testpage_obj.json_data)

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.