Skip to content

Instantly share code, notes, and snippets.

@dustinleer
Created June 21, 2022 17:21
Show Gist options
  • Save dustinleer/9146dc618841c9d8e732abe6e6652122 to your computer and use it in GitHub Desktop.
Save dustinleer/9146dc618841c9d8e732abe6e6652122 to your computer and use it in GitHub Desktop.
Syncs ACF JSON upon theme activation
<?php
/**
* Sets path for ACF json
* This is going to generate local JSON copies in your given folder for each ACF Group.
* When the ACF Group is saved/updated,
*/
define( 'IP_ACF_PLUGIN_DIR_PATH', untrailingslashit( plugin_dir_path( __FILE__ ) ) );
function ip_acf_json_save_point( $path ) {
// Update path
$path = IP_ACF_PLUGIN_DIR_PATH . '/acf-json';
// Return path
return $path;
}
add_filter( 'acf/settings/save_json', 'ip_acf_json_save_point' );
/**
* Sets the load for ACF json
*
* 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 ip_acf_json_load_point( $paths ) {
// Remove original path
unset( $paths[0] );// Append our new path
$paths[] = IP_ACF_PLUGIN_DIR_PATH . '/acf-json';
return $paths;
}
add_filter( 'acf/settings/load_json', 'ip_acf_json_load_point' );
/**
* Adds auto sync for ACF json
* When the them is distributed, on activation it will also activate ACF, then copy all the json files and execute them.
* This should automatically sync all the field groups.
* The ACF plugin can now be hidden, none of the users have to go inside ACF to sync fields.
*/
function ip_sync_acf_fields() {
// vars
$groups = acf_get_field_groups();
$sync = array();
// bail early if no field groups
if ( empty( $groups ) ) {
return;
}
// find JSON field groups which have not yet been imported
foreach ( $groups as $group ) {
// vars
$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;
}
}
// bail if no sync needed
if ( empty( $sync ) ) {
return;
}
//if( ! empty( $keys ) ) {
if ( ! empty( $sync ) ) {
// vars
$new_ids = array();
//foreach( $keys as $key ) {
foreach ( $sync as $key => $v ) {
// append fields
if( acf_have_local_fields( $key ) ) {
$sync[ $key ][ 'fields' ] = acf_get_local_fields( $key );
}
// import
$field_group = acf_import_field_group( $sync[ $key ] );
}
}
}
add_action( 'admin_init', 'ip_sync_acf_fields' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment