Using a javascript file to access a get posts array

I would like to use arrows to dynamically change which posts appear in a div by cycling through an array of say 5 posts. How would i approach this issue?

I have made the array that the get posts function is assigned to a global variable, but that’s the only thing i have done so far, as I am kind of stumped. I tried using the debug log to print the array to get some sense of how to use it, but it doesn’t make any sense at all.

Would this have something to do with wp_localize_script()? Also I’m looking to have three of these on my front page so, if I use wp_localize_script() can i use this three times? To pass three separate arrays of posts?

Solutions Collecting From Web of "Using a javascript file to access a get posts array"

Yep, you’re looking for wp_localize_script(). Do away with the global.

add_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' );
function wpse_enqueue_scripts() {
    wp_enqueue_script( 'wpse-main', get_template_directory_uri() . '/path/to/script.js', array(), false, true );
    wp_localize_script( 'wpse-main', 'wpseVars', array(
        'postsLoop1' => json_encode( /* first post array */ ),
        'postsLoop2' => json_encode( /* second post array */ ),
        'postsLoop3' => json_encode( /* third post array */ )
    ) );

Then in your script, you can access the variables by grabbing wpseVars.postsLoop1, wpseVars.postsLoop2, etc.