I have a JSON file stored in my child theme directory: file.json). Separately, the PHP template for my page contains some JavaScript code (in the form of a <script>
tag). In that JS code, I want to write the contents of the JSON file to a variable. What is the proper approach to this?
- Can/should I enqueue the JSON file, just as I would a normal JS file (i.e.
wp_enqueue_scripts()
)? If so, how would I in-turn write the contents of the file to a JS variable? Would I do something likemyJson = json.parse('.json'
)? - Can I just use
include
to include the JSON file on the page? Actually now that I think about it, one can only useinclude
with certain file extensions--correct? - Should I perhaps use PHP to save the contents of the JSON file to a PHP variable, then pass that variable to the JS code?
Thanks in advance.
I have a JSON file stored in my child theme directory: file.json). Separately, the PHP template for my page contains some JavaScript code (in the form of a <script>
tag). In that JS code, I want to write the contents of the JSON file to a variable. What is the proper approach to this?
- Can/should I enqueue the JSON file, just as I would a normal JS file (i.e.
wp_enqueue_scripts()
)? If so, how would I in-turn write the contents of the file to a JS variable? Would I do something likemyJson = json.parse('http://example/wp-contents/themes/your-theme/file.json'
)? - Can I just use
include
to include the JSON file on the page? Actually now that I think about it, one can only useinclude
with certain file extensions--correct? - Should I perhaps use PHP to save the contents of the JSON file to a PHP variable, then pass that variable to the JS code?
Thanks in advance.
Share Improve this question asked Jan 28, 2020 at 10:13 cag8fcag8f 1,9973 gold badges21 silver badges31 bronze badges2 Answers
Reset to default 1You can do this with PHP indeed. The steps are as followed;
- Get the contents of the JSON file within a variable using
$json = file_get_contents('path-to-file.json')
- Inside your
<script>
tags parse the JSON contents within a Javascript variable like this;var jsonContent = '<?= $json; ?>';
- Debug the contents in your Javascript environment using the following;
console.log(JSON.parse(jsonContent));
Sure thing, here's another method.
- First, declare the root of your templates folder inside a javascript variable like this
var rootFolder = '<?= get_template_directory_uri() ?>';
- Set the location of your JSON file within a new variable like
var jsonFile = rootFolder + '/json/file.json';
- You can use jQuery to quickly grab the contents of the file like this
<script>
var rootFolder = '<?= get_template_directory_uri() ?>';
var jsonFile = rootFolder + '/json/file.json';
$.getJSON(jsonFile, function(data) {
// Log the data to check its validity
console.log(data);
});
</script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744794381a4594115.html
评论列表(0条)