Search code examples
phpwordpressforeachadvanced-custom-fields

loop through Wordpress Custom Post Type ACF field and get unique values


I want to loop through Wordpress custom post type career field country all values and get each field value once to use them for filtering. It should likely be something similar to i.e:

$field_key = "field_64c18961a77a3";
$field = get_field_object($field_key);

if( $field )
{
    echo '<div class="acf-location-values">';
        foreach( $field['value'] as $k => $v )
        {
            echo '<a data-filter=.'.$k.' onclick="return false;">' . $v . '</a>';
        }
    echo '</div>';
}

The field setup in a plugin:

array(
        'key' => 'field_64c18961a77a3',
        'label' => 'Country',
        'name' => 'country',
        'aria-label' => '',
        'type' => 'text',
        'instructions' => '',
        'required' => 0,
        'conditional_logic' => 0,
        'wrapper' => array(
          'width' => '',
          'class' => '',
          'id' => '',
        ),
        'default_value' => '',
        'maxlength' => '',
        'placeholder' => '',
        'prepend' => '',
        'append' => '',
      ),

This doesn't seem to be giving me the expected result though (Warning: Invalid argument supplied for foreach()) - how to achieve this? Any advice appreciated.

EDIT:

var_dump for $field:

array(23) { ["ID"]=> int(0) ["key"]=> string(19) "field_64c18961a77a3" ["label"]=> string(7) "Country" ["name"]=> string(7) "country" ["aria-label"]=> string(0) "" ["prefix"]=> string(3) "acf" ["type"]=> string(4) "text" ["value"]=> string(2) "EE" ["menu_order"]=> int(5) ["instructions"]=> string(0) "" ["required"]=> int(0) ["id"]=> string(0) "" ["class"]=> string(0) "" ["conditional_logic"]=> int(0) ["parent"]=> string(19) "group_64c188737eb46" ["wrapper"]=> array(3) { ["width"]=> string(0) "" ["class"]=> string(0) "" ["id"]=> string(0) "" } ["default_value"]=> string(0) "" ["maxlength"]=> string(0) "" ["placeholder"]=> string(0) "" ["prepend"]=> string(0) "" ["append"]=> string(0) "" ["_name"]=> string(7) "country" ["_valid"]=> int(1) }

If I use $field['value'] I still get a invalid argument. Should I put the foreach in a loop for the posts?


Solution

  • Solved the issue by getting the value from each field

    $value = get_field('location');  
    $all_attributes[] = $value;
    

    And then creating a unique array based on the $all_attributes array:

    <?php 
    /* use array_unique to remove duplicates from the array */
    $filter_attributes = array_unique ($all_attributes);
    /* display the values on the same line, separated by spaces */
    echo implode(" ", $filter_attributes ); ?>