Convert ACF Fields Registered by PHP to Importable JSON Format
ACF, PHP, WordPress
When using the WordPress Advanced Custom Fields plugin, you may need to switch between PHP registered custom fields and JSON registered fields.
Use Case
In older projects we registered ACF fields by importing to PHP. This is good for the deployed site - the fields load quicker, and users can’t amend the fields.
This can be problematic if you import a production database into a local development environment. The fields are not registered in the production database. When you import it, you no longer have access to the fields in the ACF GUI. The fields still exist (they are registered by PHP functions), but you can’t use the nifty ACF interface to edit them.
Because of this we have switched to ACFs local JSON option. ACF writes the field registration data in JSON format to a server-writable directory (acf-json
, unless you override the default) in the theme root. You end up with a separate JSON file for each field group. The JSON configuration files can go into your version control system. You can deploy to staging or production, and if you accidentally delete files in your dev environment (for example, if you import a database) you can easily re-sync the JSON files to have them show up in the ACF GUI again.
If you have your fields registered by PHP (not in the database), how do you switch to the local JSON workflow?
- Create a JSON configuration file that can be read by the ACF “Import” function - i.e. mimic the output of the ACF “Export” function
- Create
acf-json
in your theme root and runsudo chown www-data acf-json
- Import the JSON file to ACF
Creating the JSON File for Import
The following quick and dirty method is suitable for a local development environment:
- Drop the code below into a suitable template
- Create a suitable config file -
touch acf-import.json
and make it server-writable - Hit the page template in your browser - you’ll see the JSON data output, and this will be written to the config file
- Import the config file: within the ACF “Tools” > “Import Field Groups” interface, select the file and click import
The field configurations are now held in the local database, and will be saved in the acf-json
directory.
comments powered by Disqus