Skip to content

Instantly share code, notes, and snippets.

@theJasonJones
Last active July 24, 2024 18:02
Show Gist options
  • Save theJasonJones/7061b8020e43a114756214e20c4d0ed9 to your computer and use it in GitHub Desktop.
Save theJasonJones/7061b8020e43a114756214e20c4d0ed9 to your computer and use it in GitHub Desktop.
Auto Populate Wordpress ACF Repeater values

Add default values to ACF Repeater Fields

I came across this solution when I had about a ton of posts (200+) with values in various PDFs. I didn't want to have to spend time filling out the same values over and over again.

Walkthrough

This case is pretty straight forward; I have one repeater field field_123a56b7cb890 that has a text fields inside it (field_588a24c3cb782). I haven't tried any other types like post objects or radio buttons, but I'm sure it can be done.

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

Step 2. Check the post_status to see if it is set to 'auto-draft', this is WP default when you create new post. If you want to override current values in posts you can change it to 'publish'

Step 3. Set $value to your array of default values. Above, I have 4 rows by default on new posts. Each post_type had different values so I check the post_type and add the values that way.

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

// Add field key of the repeater
add_filter('acf/load_value/key=field_123a56b7cb890', 'afc_load_my_repeater_value', 10, 3);
function afc_load_my_repeater_value($value, $post_id, $field) {
//Optional: Check for post_status otherwise published values will be changed.
if ( get_post_status( $post_id ) === 'auto-draft' ) {
//Optional: Check for post_type.
if( get_post_type( $post_id ) == 'cpt_type_1' ){
$value = array();
// Add field key for the field you would to put a default value (text field in this case)
$value[] = array(
'field_588a24c3cb782' => 'Tank:'
);
$value[] = array(
'field_588a24c3cb782' => 'Dimensions:'
);
$value[] = array(
'field_588a24c3cb782' => 'Weight:'
);
$value[] = array(
'field_588a24c3cb782' => 'Base:'
);
}
if( get_post_type( $post_id ) == 'cpt_type_2' ){
$value = array();
$value[] = array(
'field_588a24c3cb782' => 'Capacity:'
);
$value[] = array(
'field_588a24c3cb782' => 'Load Rating:'
);
$value[] = array(
'field_588a24c3cb782' => 'Dumping Methods:'
);
$value[] = array(
'field_588a24c3cb782' => 'Color:'
);
}
}
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment