Forked from jessepearson/acf-update-via-json.php
Last active
October 19, 2021 00:03
-
-
Save nkkollaw/8f0b0047fb6fc4a000bc975719fec682 to your computer and use it in GitHub Desktop.
Automatically update Advanced Custom Fields field groups via JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Function that will automatically update ACF field groups via JSON file update. | |
* | |
* @link http://www.advancedcustomfields.com/resources/synchronized-json/ | |
*/ | |
function jp_sync_acf_fields($json_dirs) { | |
$groups = acf_get_field_groups(); | |
if (empty($groups)) { | |
return; | |
} | |
// find JSON field groups which have not yet been imported | |
$sync = array(); | |
foreach ($groups as $group) { | |
$local = acf_maybe_get($group, 'local', false); | |
$modified = acf_maybe_get($group, 'modified', 0); | |
$private = acf_maybe_get($group, 'private', false); | |
// ignore DB / PHP / private field groups | |
if ($local !== 'json' || $private) { | |
// do nothing | |
} elseif (! $group['ID']) { | |
$sync[$group['key']] = $group; | |
} elseif ($modified && $modified > get_post_modified_time('U', true, $group['ID'], true)) { | |
$sync[$group['key']] = $group; | |
} | |
} | |
if (empty($sync)) { | |
return; | |
} | |
foreach ($sync as $key => $group) { //foreach ($keys as $key) { | |
// append fields | |
if (acf_have_local_fields($key)) { | |
$group['fields'] = acf_get_local_fields($key); | |
} | |
// import | |
$field_group = acf_import_field_group($group); | |
} | |
// sync groups that have been deleted | |
if (!is_array($json_dirs) || !$json_dirs) { | |
throw new \Exception('JSON dirs missing'); | |
} | |
$delete = array(); | |
foreach ($groups as $group) { | |
$found = false; | |
foreach ($json_dirs as $json_dir) { | |
$json_file = rtrim($json_dir, '/') . '/' . $group['key'] . '.json'; | |
if (is_file($json_file)) { | |
$found = true; | |
break; | |
} | |
} | |
if (!$found) { | |
$delete[] = $group['key']; | |
} | |
} | |
if (!empty($delete)) { | |
foreach ($delete as $group_key) { | |
acf_delete_field_group($group_key); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, thanks for this good code.
I have modified it because that seems better to delete before to update. For example : you have three fields groups and so three json files and you delete this three json files, your code will be played until line 10 and will stop because $groups is empty. So in admin I still have three groups while there are no json files at all.
If I delete groups before update groups, I have no more groups in BO and no more json files.
That seems ok for you ? : https://gist.github.com/superpositif/85d14af60894520ab122f96e0fd046a6