Home › Forums › General Issues › Set field group programatically
Hi I’m having a bit of a problem with setting the location for a field group in my functions.php file. The code below adds a location of ‘entrant_2025’ only if it doesn’t already exist as a selected location in the location array.
It works fine. The fields gets added to the custom post type and I can also see it as a selected option in the field group location settings in the ACF UI.
The problem comes when I save the field group in the UI for whatever reason such as making a change or adding a new field. Each time I click save, another location gets added for ‘entrant_2025’.
Here is the code:
add_filter( 'acf/validate_field_group', 'add_custom_location_dynamic', 10, 1 );
function add_custom_location_dynamic( $field_group ) {
if ( $field_group['key'] === 'group_6786e0728946a' ) {
$location = false;
foreach($field_group["location"] as $loc){
if(in_array('entrant_2025', $loc[0])){
$location = true;
}
}
if(!$location){
$field_group['location'][][0] = array(
'param' => 'post_type',
'operator' => '==',
'value' => 'entrant_2025',
);
}
}
return ($field_group);
}
I dont know for sure what is happening but I presume ACF doesn’t see or recognise my saved location and so adds the location again and again and again each time I save.
I’ve tried changing the priority of 10 to much higher to see if that helps to run the code after acf has run it’s own or way lower to see if ACF will recognise the saved location and therefore not save another one but nothing works.
Any pointers would be a great help. Thanks.
This fixed it which means I was wrong in my assumptions above. I just basically overwrote the existing locations array and everything works fine:
add_filter( 'acf/validate_field_group', 'add_custom_location_dynamic', 10, 1 );
function add_custom_location_dynamic( $field_group ) {
if ( $field_group['key'] === 'group_6786e0728946a' ) {
// This line below clears any existing locations
$field_group['location'] = array();
$currentYear = get_field('current_year', 'option');
$awardArgs = createYearArray($currentYear);
// $awardArgs is just an array of ["2024", "2025"]
$x=0;
foreach($awardArgs as $year) {
$field_group['location'][$x][] = array(
'param' => 'post_type',
'operator' => '==',
'value' => 'entrant_'.$year,
);
$x++;
}
}
return ($field_group);
}
Hope that helps anyone else looking for this.
Ciptakan pengalaman pelanggan whatsapp api yang tak terlupakan!
You must be logged in to reply to this topic.
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.