Back in the day, if you wanted to make sure you could keep your environments in sync (and you couldn’t just be moving the database around) you had to use PHP to build and update your ACF forms. It was gross.
Nowadays you can just work with the ACF fields in the admin like normal and ACF will AUTOMAGICALLY build a json form you can use to sync your different environments.
You do need to set this up a little bit, so stick this in your functions.php file to get started.
1 2 3 4 5 6 7 8 9 |
//Pick a place for your jsons to live. We stick them into the /theme/includes/acf-json folder, but you can stick these wherever // change where acf json files are saved add_filter('acf/settings/save_json', 'jb_acf_save_json'); function jb_acf_save_json($path) { return get_stylesheet_directory().'/includes/acf-json'; } // add our custom folder to places acf json are loaded from add_filter('acf/settings/load_json', 'jb_acf_load_json'); function jb_acf_load_json($paths) { return array_merge($paths, array(get_stylesheet_directory().'/includes/acf-json')); } |
Now the tricker part is going to be converting your old PHP.
I just setup a script like the one below and ran it once. This script is taken fromĀ David Egan’s site.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//this file is in the root of the site. Since this is only run once we can even delete this file immediately after we run it define('WP_USE_THEMES', false); require_once('wp-load.php'); $groups = acf_get_local_field_groups(); $json = []; foreach ($groups as $group) { // Fetch the fields for the given group key $fields = acf_get_local_fields($group['key']); // Remove unecessary key value pair with key "ID" unset($group['ID']); // Add the fields as an array to the group $group['fields'] = $fields; // Add this group to the main array $json[] = $group; } $json = json_encode($json, JSON_PRETTY_PRINT); // Optional - echo the JSON data to the page echo $json; // Write output to file for easy import into ACF. // The file must be writable by the server process. In this case, the file is located in // the current theme directory. $file = get_template_directory() . '/acf-import.json'; file_put_contents($file, $json ); |
All you need to do now is copy the output from this script into it’s own file (or you could just have PHP write that file for you) and save it as a .json.
IMPORTANT NOTE: At this point this json file probably wont work. I had to go through the file and double quote all of the keys and fix up some other formatting issues. This was 99% completed by just doing a single find and replace in Visual Studio Code. Regex: /”\s\w+:”/ This should find MOST of your keys and correctly format them so ACF can import them. This wont work PERFECTLY so you will need to scan your file to make sure everything is formatted right, but it will get you 99% of the way there.
Good Luck!