GuitarExtended
GuitarExtended

Reputation: 827

Path to load a file from Javascript in WordPress site

I'm developping a website using WordPress in which I need to include some data-vis made with javascript. I need to load a file containing data in my JS script. Both the script and the data are located in my theme's folder with the following hierarchy :

theme
--scripts
----my_script.js
--data
----my_data.csv

Say I use d3.js to load the data in my script, using the following code :

d3.csv("path/to/data/my_data.csv", function(error, data){
    // Use the data
});

What should path/to/data be ? I'm very confused. Should it be relative to where the script is ? Or to where the page using the script is ? Relative to the server filesystem, or to the site's domain ?

Upvotes: 0

Views: 291

Answers (1)

GuitarExtended
GuitarExtended

Reputation: 827

Since I didn't get any answers yet, here's what I ended up doing.

In the page template in which the visualizations are to be displayed, I added the following code to the body :

<script>
var theme_URI = "<?php echo get_stylesheet_directory_uri(); ?>";
</script>

This uses a WordPress function to get the path to the current theme, so getting the correct path to my data files is now trivial :

d3.csv(theme_URI + "/data/my_data.csv", function(error, data){
    // Use the data
});

Upvotes: 1

Related Questions