Saving the ACF JSON locally to your plugin or theme file | Save, Load and Sync Advanced Custom Fields JSON

Saving the ACF JSON files locally allows you to have version control over your field settings! Let’s learn how to do that.

Create an acf-json directory

  • Create a directory called acf-json in your plugin.

Save the JSON

Add the following in your functions.php file

<?php
define( 'MY_PLUGIN_DIR_PATH', untrailingslashit( plugin_dir_path( __FILE__ ) ) );add_filter('acf/settings/save_json', 'my_acf_json_save_point');
 
function my_acf_json_save_point( $path ) {
    
    // Update path
    $path = MY_PLUGIN_DIR_PATH. '/acf-json';
    // Return path
    return $path;
    
}
 
?>

Now when you hit save/update for each ACF Group , it is going to generate a local JSON copies in your given folder for each ACF Group.

In my case I have two ACF Group, so it has generated two files.

Load the JSON

During ACF’s initialization procedure, all .json files within the acf-json folder will be loaded. By default ACF looks for a folder within your theme called acf-json, however, this is only 1 of the load points which can be added.
Let’s add a new load point removing the existing ones.

<?php 

add_filter('acf/settings/load_json', 'my_acf_json_load_point');

/**
 * Register the path to load the ACF json files so that they are version controlled.
 * @param $paths The default relative path to the folder where ACF saves the files.
 * @return string The new relative path to the folder where we are saving the files.
 */
function my_acf_json_load_point( $paths ) {
   // Remove original path
   unset( $paths[0] );// Append our new path
   $paths[] = MY_PLUGIN_DIR_PATH. '/acf-json';   return $paths;
}

?>

Syncing the ACF

JSON field groups will be available for sync when either the JSON field group does not exist in the DB, or when the JSON field group contains a higher ‘modified’ value (within the JSON array) than the DB post’s modified date.

This helps multiple developers working on the same project to share the updates. Once new ACF changes/updates are pushed, a sync will be available in ACF Field Groups in dashboard. You can click on the sync to save changes.

A similar process can be followed for theme as well.

That’s all folks!

Leave a Reply