Booker

Saturday, January 28, 2017

Filter for retrieving select field items

The following code needs to be put inside your theme functions.php

/**
 * @param $group_NAME
 * @return array
 */
function fetchACFFields($group_NAME)
{
 // Fetch fields for a given ACF fields group (PRO only)
 $groups = acf_get_field_groups();
 $fields_group = [];
 foreach ($groups as $group) {
  $title = $group['title'];
  if ($title == $group_NAME) {
   $f = acf_get_fields($group['ID']);
   foreach ($f as $i) {
    $fields_group[$group['title']]['fields'][$i['name']] = $i;
    $fields_group[$group['title']]['fields'][$i['name']]['value'] = get_field($i['key']);
   }
   break;
  }
 }
 return $fields_group;
}
add_filter( 'fetch_acf_fields', 'fetchACFFields', 10, 2 );

/**
 * @param $fields_group
 * @param $mysubfield
 * @return array
 */
function fetchSubfieldChoices($group_NAME, $mysubfield)
{
 $fields_group = apply_filters('fetch_acf_fields', $group_NAME);
 // Find choices from subfield
 $first_key = array_keys($fields_group)[0];
 $root = $fields_group[$first_key];

 $choices = [];
 foreach ($root['fields'] as $subfield) {
  foreach ($subfield['sub_fields'] as $sub_field) {
   $sub_field_name = $sub_field['name'];

   if ($sub_field_name == $mysubfield) {
    $choices = $sub_field['choices'];
   }
  }
 }
 return $choices;
}

add_filter( 'fetch_subfield_choices', 'fetchSubfieldChoices', 10, 2 );
and then execute:
/**
$choices = apply_filters('fetch_subfield_choices', $group_NAME, $mysubfield);