Wordpress: Getting an php Array into JS-Function Wordpress: Getting an php Array into JS-Function wordpress wordpress

Wordpress: Getting an php Array into JS-Function


I don't know the structure of your array but you can use json_encode($images) and pass the data in a JS variable using wp_localize_script. So in functions.php you do this:

$images = get_field('galerie');$images = json_encode($images);wp_enqueue_script( 'my_js_file', get_template_directory_uri() . '/js/custom.js' );$data_to_send = array(    'images' => $images);wp_localize_script( 'my_js_file', 'object_name', $data_to_send );

And then in your javascript file custom.js you can get what you need like this:

var my_images = JSON.parse(object_name.images);var imagesToAppend = [];for(var i = 0; i < my_images.length; i++){    var img_src = my_images[i].url;    imagesToAppend[i] = { src: img_src };}console.log(imagesToAppend);$(".slider").vegas({      slides: imagesToAppend  });

Notice that you have to parse the response string using JSON.parse.

A simplified solution would be to change the name of the url to src from ACF so you don't have to use that loop and change the keys for the object to src and then you can just append my_images to the Vegas slider init, like this:

var my_images = JSON.parse(object_name.images);$(".slider").vegas({  slides: my_images});

Also, if you're including the custom.js script in other way then I exemplified above, please remove that, or you will get the same response twice.

It really depends on your array structure, but this should work.

Also, you can read more about wp_localize_script here.