· 4 years ago · Mar 31, 2021, 11:52 AM
1<?php
2
3function my_acf_add_local_field_groups() {
4    include_once( get_theme_file_path('./helpers/env.php') );
5
6    $END_POINT        = get_env_name('SAS_URL') . get_env_token('SAS_TOKEN');
7    $json_data        = @file_get_contents($END_POINT);
8    $consultants_data = json_decode($json_data, TRUE);
9
10    // Getting all of the categories name from API 
11    foreach ($consultants_data as $key => $consultant) {
12        if ( $consultant['cv']['technologies'] ) {
13            foreach ($consultant['cv']['technologies'] as $skills) { 
14                asort($skills);
15                $category = $skills['category']['no'];
16
17                if(!empty($category)) {
18                    $category_data[] = [ $category ];
19                }
20            }
21        }
22    }
23
24    // Remove duplicated values and keep only one value instead 
25    $categories_arr = array_unique([...$category_data], SORT_REGULAR );
26    sort($categories_arr);
27
28    // Creating a ACF fields of 'text'. We are going to use it to append it to produce many fields categories
29    foreach (array_flatten($categories_arr) as $index => $category) {
30        $fields[] = [
31            'key' => 'field_' . $index,
32            'label' => $category,
33            'name' => $category,
34            'type' => 'text',
35        ];
36    }
37
38    // Generating fields
39    foreach ($fields as $field) {
40        acf_add_local_field_group(array(
41            'key' => 'group_5d070117d8065',
42            'title' => 'Konsulentfelter',
43            'fields' => [ $field ], 
44            'location' => array (
45                array (
46                    array (
47                        'param' => 'post_type',
48                        'operator' => '==',
49                        'value' => 'konsulenter',
50                    ),
51                ),
52            ),
53        )); 
54    }
55}
56
57add_action('acf/init', 'my_acf_add_local_field_groups');
58
59function array_flatten($array) { 
60  if (!is_array($array)) { 
61    return false; 
62  } 
63  $result = array(); 
64  foreach ($array as $key => $value) { 
65    if (is_array($value)) { 
66      $result = array_merge($result, array_flatten($value)); 
67    } else { 
68      $result = array_merge($result, array($key => $value));
69    } 
70  } 
71  return $result; 
72}