JavaScript, best way to use data from the loop

I am trying to learn WP theme development. And at the moment I am trying to figure out how to use data from the loop in JavaScript.

Lets say I got some JavaScripts functions in a external script-file loaded with wp_enqueue. And that this script needs to usa alot of data from the meta for posts.

What is best practice to get this data from the loop to my script. Should I loop the data out to global JavaScript Arrays or Object that my script then use? What is “best practice”? I am especially thinking about “to keep JavaScript code away from the templates, and should only be loaded from external files”.

I have also read somewhere that when you use global variables, arrays or object in WP you need to comment this in the top of the file? Is this correct? And what exactly should I write in this comment head?

1 Answer
1

You can use WP_Query to get almost any post data out of your WordPress install.

$sub_pages = new WP_Query(
    array( 
        'post_parent' => 3,
        'post_type' => 'page'
    )
);

print_r($sub_pages->posts);

This would get you the following:

Array
(
    [0] => WP_Post Object
        (
            [ID] => 94
            [post_author] => 1
            [post_date] => 2015-08-20 11:19:27
            [post_date_gmt] => 2015-08-20 10:19:27
            [post_content] => Business operating...

An array full of posts. So all you need to do is json encode this, and wrap it in script tags.

<script type="text/javascript">
    var post_info = <?php echo json_encode($sub_pages->posts); ?>;
</script>

This will output:

<script type="text/javascript">
    var post_info = [{"ID":94,"post_author":"1","post_date":"2015-08-20 11:19:27","post_date_gmt":"2015-08-20 10:19:27","post_content":"Business operating

So now, if I put this before where I load my JavaScript, i.e

<script type="text/javascript">
    var post_info = <?php echo json_encode($sub_pages->posts); ?>;
</script>
<script type="text/javascript" src="https://wordpress.stackexchange.com/questions/200464/script.js"></script>

In script.js I can just go

console.log(post_info[0].ID);

And we’ll get 94 in the console.

Leave a Comment