Home › Forums › Add-ons › Repeater Field › Dynamically Populating Repeater › Reply To: Dynamically Populating Repeater
The simplest fix is at the beginning of your function you need to see if the field already has a value.
function treatment_prices( $value, $post_id, $field ) {
if (!empty($value)) {
return $value;
}
However, I don’t think that’s going to be your best solution for the future.
Since you are dynamically adding the fields based on another field what you really need to do is to compare what’s already in the repeater with the selected terms. Add any taxonomies that were not there the last time and remove any that are no longer selected.
function treatment_prices( $value, $post_id, $field ) {
$terms = wp_get_post_terms($post_id, 'treatment', array( 'orderby' => 'term_id'));
$selected_terms = array();
$existing_terms = array();
$new_value = array();
// collect list of selected terms
if ($terms) {
foreach ($terms as $term) {
// we are setting the key and value so that we can unset it if it already exists
$selected_terms[$term->name] = $term->name
}
}
// loop though the rows
// collect list of existing terms
// if the existing term is in selected terms then add it to the output
if (is_array($value)) {
foreach ($value as $row) {
if (in_array($row['field_5bd192adfde26'], $selected_terms)) {
// unset this from selected terms if it exists
if (isset($selected_terms['$row['field_5bd192adfde26']])) {
unset($selected_terms['$row['field_5bd192adfde26']]);
}
// add row to output
$new_value[] = $row;
}
}
}
// loop over selected terms and add any new ones, if any
if (count($selected_terms)) {
foreach ($selected_terms as $name) {
$new_value[] = array('field_5bd192adfde26' => $name);
}
}
return $new_value;
}
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.