Support

Account

Home Forums Add-ons Repeater Field get_field() for repeater returning string instead of array Reply To: get_field() for repeater returning string instead of array

  • Hi!

    Thanks to this post i was able to figure out what was going on. In case it helps anyone out there:

    In my website settings I have defined a series of one-column repeaters that hold values that the user can enter. When I was getting these options in hooks that attached to ‘acf/load_field/key=’ getting the repeater yielded the expected behaviour, but sometimes it just returned the size of the repeater.

    To get around this, I wrote this code that takes in the repeater name and the column you are after. It uses the ACF API when possible or otherwise falls back on the WordPress API to obtain the value.

    Makes me wonder if I should just stick to the WP API to improve performance? 🤔

    
    	public function get_repeater_option_values( $repeater_name = '', $repeater_column_name = '' ) {
    		$associative_array = array();
    		$repeater_instance = \get_field( $repeater_name, 'option' );
    
    		if ( \is_array( $repeater_instance ) ) { // get_field( 'repeater_name', 'option') gets a repeater instance.
    			$repeater_instance = \get_field( $repeater_name, 'option' );
    			$setting_values    = array_column( $repeater_instance, $repeater_column_name );
    			foreach ( $setting_values as $key => $value ) {
    				$associative_array[ str_replace( ' ', '_', strtolower( $value ) ) ] = $value;
    			}
    		} else { // get_field( 'repeater_name', 'option' ) returns the repeater size.
    			$repeater_size = $repeater_instance;
    			for( $i = 0; $i < $repeater_size; $i++ ) {
    				$value =  \get_option( "options_{$repeater_name}_{$i}_{$repeater_column_name}" );
    				$associative_array[ str_replace( ' ', '_', strtolower( $value ) ) ] = $value;
    			}
    		}
    		return $associative_array;
    	}