Access a local JSON file in WordPress Theme

I am dynamically creating a JSON file of data when a user saves a page in the WordPress backend. I’m doing this through the hook ‘save_post’ and saving the file ‘network.json’ using file_put_contents to the root of my theme folder. I’m doing this so I can access specific data from a js script in my theme.

Current Approach
I have a js file enqueued into my theme with the following JS inside of it. The below is working but I’m wondering if it is the best approach for calling a local JSON file within a WP theme.

$.getJSON( "../wp-content/themes/ihdf/network.json", function(data) {

Is the above the proper and most technically sound way of doing it?

Other Approaches

I’ve previously used ajax in WordPress by enqueuing a script and setting up the proper ajax function to call with admin-ajax.php. That seems overly complicated for my needs.

I could also set a js variable within my template file like the below:

var networkJSON = <?php get_template_directory_uri() . '/network.json' ?>

Read more here: Access a local JSON file in WordPress Theme

Leave a Reply

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