Support

Account

Home Forums ACF PRO Populate repeater in CPT from repeater in Options page Reply To: Populate repeater in CPT from repeater in Options page

  • This is really 2 questions, I’m going to answer one at a time.

    The first, how to pre load a repeater field on a new post from a repeater in the options field.

    If the repeater and all of the sub fields are the same, so the two repeaters are identical, the it’s kinda easy, you just need to get the value from the options page and return in. What I did was I created a field group that contained my repeater and assigned it to both a CPT and an Options page, making them identical.

    
    add_filter('acf/load_value/key=field_56e870552a8c1', 'load_repeater_value', 10, 3);
    function load_repeater_value($value, $post_id, $field) {
      if ($value !== NULL) {
        // on a new post the value will === NULL
        // if the value is not exactly NULL then bail
        return $value;
      }
      $new_value = get_field('repeater', 'option', false);
      
      // you can see this value if you uncomment the next line
      //echo '<pre>'; print_r($new_value); echo '</pre>';
      
      // if the repeaters are identical
      $value = $new_value;
      
      return $value;
    }
    

    On the other hand, If the repeaters are not identical and the repeater on the CPT has different field keys than the repeater on the Options page, or they are different is some other way then you have a lot of work to do. Comment out the line assigning the new value and uncomment the line that outputs the value gotten from the options page. What you’ll need to do is to build a new array using the correct field keys for the repeater located on the CPT.

    The format of the array you need to return is

    
    $value = array(
        // a nested array for each row
        array(
            // key value pair for each sub field
            'field_123456789' => $value,
            // the next one is a nested repeater
            'field_987654321' => array(
                // a nested array for each row
                array(
                // key value pair for each sub_field
                'field_784ab6767' => $vlaue
               )
            )
         )
    );