user13286
user13286

Reputation: 3075

Wordpress - Pass PHP array from ACF repeater to JavaScript file

I am using Wordpress and Advanced Custom Fields to loop through a list of YouTube videos. What I would like to do is create a PHP array in my template of all the video IDs and then pass that array to an external JavaScript file. I think this can be done with wp_localize_script but I'm not exactly sure how to do it. Here's what I have so far:

functions.php:

global $video_ids;
wp_register_script('player', get_template_directory_uri() . '/js/player.js', array('jquery'), '1.0', true);
wp_enqueue_script('player');
wp_localize_script('player', 'videos',
  array( 
    'video_ids' => $video_ids
  )
);

single.php:

<?php global $video_ids; $video_ids = array(); ?>
<?php if(have_rows('videos')):
        while (have_rows('videos')) : the_row(); 
            array_push($video_ids, get_sub_field('video_id'));
        endwhile;
    endif;
?>

player.js:

console.log(videos.video_ids);

Right now the console log is returning null but when I print_r the $video_ids array on the single.php template it is correctly displaying the array. What am I missing?

Upvotes: 1

Views: 753

Answers (1)

mahmoudayoub
mahmoudayoub

Reputation: 906

You have the array in PHP but you're trying to access it in javascript. The following should solve your problem, it encodes the php array as json and echoes it inside a script variable so it can be accessed in javascript. Paste it below your code in single.php like this

<?php global $video_ids; $video_ids = array(); ?>
<?php if(have_rows('videos')):
        while (have_rows('videos')) : the_row(); 
            array_push($video_ids, get_sub_field('video_id'));
        endwhile;
    endif;
?>

<script type='text/javascript'>
    <?php
        $ids = json_encode($video_ids);
        echo "var videos = ". $ids . ";\n";
    ?>
    videos.forEach(video => console.log(video));
</script>

Upvotes: 1

Related Questions