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' )

  • Thank you so much @hube2! 🙂 I really appreciate your feedback and for sharing your code. Here is what I ended up using. I kept your naming convention for convenience.

    
    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
    		add_filter( 'acf/prepare_field/key=field_601cf9424f9da', array( $this, 'init_my_field_name_index' ), 10, 1 );
    		
    		add_filter( 'acf/prepare_field/key=field_6023ad409d89d', array( $this, 'filter_my_sub_field_name' ), 10, 1 );
    		
    		// add filter for ths sub field that you want to filter
    		add_filter( 'acf/prepare_field/key=field_602e8a8821e89', array( $this, 'filter_my_sub_sub_field_name' ), 10, 1 );
    	}
    	  
    	public function init_my_field_name_index( $field ) {
    		$this->my_field_name_index = 0;
    		return $field;
    	}
    	
    	public function filter_my_sub_field_name( $field ) {
    		// after filtering increment the field index
    		$this->my_field_name_index++;
    		
    		// return the field;
    		return $field;
    	}
    	  
    	public function filter_my_sub_sub_field_name( $field ) {
    		$field['choices'] = [];
    		
    		$row_index = $this->my_field_name_index - 2;
    		
    		$product_id = (int) get_user_meta( 2, 'add_products_' . $row_index . '_produkt', true );
    		
    		if ( ! empty( $product_id ) ) {
    			
    			$pewc_group = new WP_Query( [
    				'posts_per_page => ' -1,
    				'post_type' => 'pewc_group',
    				'post_parent' => $product_id,
    				'post_status' => 'publish'
    			] );
    			if ( $pewc_group->have_posts() ) {
    				while( $pewc_group->have_posts() ) { $pewc_group->the_post();
    					
    					$field['choices'] = [];
    					
    					$group_title = get_the_title();
    					$group_id = get_the_ID();
    					
    					$pewc_field = new WP_Query( [
    						'posts_per_page => ' -1,
    						'post_type' => 'pewc_field',
    						'post_parent' => get_the_ID(),
    						'post_status' => 'publish',
    						'order' => 'ASC'
    					] );
    					if ( $pewc_field->have_posts() ) {
    						while( $pewc_field->have_posts() ) { $pewc_field->the_post();
    							$field_label = get_post_meta( get_the_ID(), 'field_label', true );
    							if ( ! empty( $field_label ) ) {
    								$field['choices'][get_the_ID()] = $field_label . ' (' . get_the_ID() . ')';
    							}
    						}
    						wp_reset_postdata();
    					}
    					
    				}
    				wp_reset_postdata();
    			}
    		}
    
    		// return the field;
    		return $field;
    	}
    	  
    }
    new MY_PROJECT_NAME_acf_filters();