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.