Support

Account

Home Forums Add-ons Repeater Field Get row index inside add_filter( 'acf/load_field' ) Reply To: Get row index inside add_filter( 'acf/load_field' )

  • You cannot populate different rows of a repeater with different row values using an acf/load_field filter. The reason is that the sub field is only “loaded” once so the field will have the same values for all rows.

    This can be accomplished using the acf/prepare_field filter. I actually just did this yesterday 🙂

    In order to do this you need to keep track of the row index yourself. I did this by encapsulating the filter in a class. This is how I set up all my filters. Basically I set up a class where I add all my ACF filters. Here is a basic example of what you want to do.

    Also, note that when filtering sub fields of a repeater it is usually best to use the field key the field name will not be what you expect it to be. For example, the field name being used by ACF for my filter looks something like this

    
    acf[field_602be12e89017][row-2][field_602be2818901b][field_602be3658901c][row-0][field_602d11a1de2fd][row-0][field_602d10bd5cc06]
    

    the field that I am filtering is a sub field in repeater that is nested in another repeater that is then nested in a group field that is nested in another repeater. It may work with the name, but it is more likely that a sub field will share it’s name with a sub field of other repeaters. For example, the name of this field is “value” and I use this sub field name often. Anyway, on to the example.

    
    class MY_PROJECT_NAME_acf_filters {
      
      // variable for row index
      private $my_field_name_index = 0;
      
      public function __construct() {
        // add a filter when preparing repeater
        // I also tend to always use field keys when coding
        add_filter('acf/prepare_field/key=field_XXXXX', array($this, 'init_my_field_name_index'));
        
        // add filter for ths sub field that you want to filter
        add_filter('acf/prepeare_field/key=field_YYYYY', array($this, 'filter_my_sub_field_name'));
      }
      
      public function init_my_field_name_index($field) {
        $this->my_field_name_index = 0;
        return $field;
      }
      
      public function filter_my_sub_field_name($field) {
        $row_index = $this->my_field_name_index;
        
        // do your filtering for this row index
        
        // after filtering increment the field index
        $this->my_field_name_index++;
        
        // return the field;
        return $field;
        
      }
      
    }