Home › Forums › Backend Issues (wp-admin) › How to dynamically remove choices from select field? › Reply To: How to dynamically remove choices from select field?
I don’t think there is a way to mark unmark a solution.
The reason it becomes an infinite loop is that you’re loading the field inside of the filter that loads the field so your filter keeps getting called. You don’t really need to get the field to get the current choices because they are already passed as part of $field
function acf_load_ad_zones_choices( $field ) {
$choiceArray = $field['choices'];
// get all ads and put ad zones attached to them into an array
$args = array(
'post_type' => 'rsc-ads',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$ads = get_posts( $args );
// array of values already in use
// will be populated with all zones used by published ads
$choicevalues = array();
foreach ($ads as $ad) {
// get ad_zones values from the ad
$advalues = get_field('ad_zones', $ad->ID);
// put all the ad_zone values into an array
foreach ($advalues as $key => $value) {
array_push($choicevalues, $value);
}
}
// reset choices
$field['choices'] = array();
$result = array_diff($choiceArray, $choicevalues);
/*
I don't really think you need to clear choices and then do the loop
but I can't tell for sure looking at your code. I think you can delete
this line above $field['choices'] = array();
and just do $field['choices'] = $results;
and then delete the following loop
*/
// loop through array and add to field 'choices'
if ( is_array($result) ) {
foreach( $result as $choice ) {
$field['choices'][ $choice ] = $choice;
}
}
// return the field
return $field;
}
add_filter('acf/load_field/key=field_59772109bf9d4', 'acf_load_ad_zones_choices');
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.