Support

Account

Home Forums Add-ons Repeater Field dynamically generate subfield content Reply To: dynamically generate subfield content

  • This has been bugging me for quite a while, but I think I’ve finally cracked it. It was almost disappointingly simple in the end – $value needs to be an array.

    
    add_filter('acf/load_value/key=field_54aa5b3b008b0',  'afc_load_my_repeater_value', 10, 3);
    function afc_load_my_repeater_value($value, $post_id, $field) {
    	if ($post_id === false) {
    		$value	= array();
    		$value[] = array(
    			field_54aa5beb008b1 => 'Hours',
    			field_54aa5c25008b2 => 1
    		);
    		$value[] = array(
    			field_54aa5beb008b1 => 'Minutes'
    		);
    		$value[] = array(
    			field_54aa5beb008b1 => 'Seconds'
    		);
    	}
    	return $value;
    }
    

    This case is pretty straight forward; I have one repeater field field_54aa5b3b008b0 that has two text fields inside it (field_54aa5beb008b1 and field_54aa5c25008b2). I imagine the same setup will apply to more in-depth scenarios as well with some tweaking.

    Step 1. Hook into acf/load_value on your repeater field. You can use type/key/name as desired here.

    Step 2. Check if the $post_id is set or not. If you want to modify the values of existing posts as well you wouldn’t need to, but here I want to set default values for new posts only.

    Step 3. Set $value to your array of default values. Above, I have 3 rows by default on new posts. Each row has two values – ‘unit of time’ and ‘amount of time’. The ‘unit of time’ values are set to “Hours”, “Minutes” and “Seconds”. The ‘amount of time’ value on the “Hours” row I have set default to 1. In the other rows, I didn’t want the second value to be set by default, so it’s omitted – if omitted, ACF uses the default value set in the admin (or just blank).

    Step 4. Return the $value. Make sure you always return it – even if you haven’t modified it.

    ———– NOTES
    – I’m using ACF Pro 5.1.8, but it should work in other versions as well (using the proper hooks as needed).
    – The sub fields appear to be required to the the exact field key – field name and type haven’t worked for me.
    – Above, I’m setting a static set of values as my defaults. You could certainly call a function or otherwise dynamically load an array into $value from elsewhere as well – just need to make sure it uses the key for sub fields.
    – If you’re not sure how the array should be set up, just print out an array from an existing repeater in the wp-admin like this:

    
    add_filter('acf/load_value/key=field_54aa5b3b008b0',  'afc_load_my_repeater_value', 10, 3);
    function afc_load_my_repeater_value($value, $post_id, $field) {
    	echo print_r($value);
    	return $value;
    }
    

    This will print out the repeater value from an existing post. Save the post with some rows in your repeater and you’ll see a guide of how to set up the array of defaults.