从 ACF 中继器推送值

Push values from ACF repeater

我创建了一个 JavaScript 函数,它在参数中接受 2 个数组,其目标是能够随机 select 每个数组的索引。 但我担心的是,我的 2 个数组的数据是通过 ACF 转发器使用 PHP 检索的。

<script>
  // I call my JS function once the page is fully loaded
  window.addEventListener('load', hook);

  // Variable declaration
  let description_list;
  let description_list_2;
</script>

<?php

// The list_name param contains the name of the repeater field
 function showSkill($list_name){
          if( have_rows($list_name) ):
            $skill = array();
  
            while( have_rows($list_name) ) : the_row();
              $sub_value = get_sub_field('quality');
    
              array_push($skill,$sub_value); 

            endwhile;

              print_r($skill);
           else :

          endif;
 }

  showSkill('description_list');
  showSkill('description_list_2');
?>

<script>
  function hook() {

    let randHook1 = description_list[Math.floor(Math.random() * description_list.length)];
    let randHook2 = description_list_2[Math.floor(Math.random() * description_list_2.length)];
    console.log(randHook1);
    console.log(randHook2);
    setTimeout(hook, 2000);
  }
</script>

您可以尝试通过 json_encode:

将 PHP 数组插入您的 JS

首先,您需要设置PHP个变量:

<?php
function showSkill( $list_name ){
  $skill = array();

  if( have_rows( $list_name ) ):

    while( have_rows( $list_name ) ) : the_row();

      $sub_value = get_sub_field( 'quality' );
      array_push( $skill, $sub_value ); 

    endwhile;

    print_r( $skill );

  endif;

  // You need to return the array
  return $skill;
}

// Get the returned array, convert to JSON and save into a variable
$description_list = json_encode( showSkill( 'description_list' ) );
$description_list_2 = json_encode( showSkill( 'description_list_2' ) );
?>

然后你可以将变量通过管道传递给 JS:

<script>

let description_list = <?php echo $description_list; ?>

// 1. Parse JSON String to Object
description_list = JSON.parse(description_list);

// 2. Convert Object to Array
description_list = Object.values(description_list);

// 3. Do the same for description_list_2, or convert this process into a function
let description_list_2 = Object.values(JSON.parse(<?php echo $description_list_2)));

</script>

并且 运行 你的 JS hook() 功能照常。