-
-
Save jessepearson/a537b2f78556cd705947 to your computer and use it in GitHub Desktop.
<?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() { | |
// 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( $sync ) ) { //if( ! empty( $keys ) ) { | |
// vars | |
$new_ids = array(); | |
foreach( $sync as $key => $v ) { //foreach( $keys as $key ) { | |
// 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', 'jp_sync_acf_fields' ); |
@saminton It's most likely due to code changes. I wrote this four years ago it looks like for a need I had at the time.
@saminton yes it did not work for certain field types for me as well so I stopped using this and went back to the PHP file method.
@saminton yes it did not work for certain field types for me as well so I stopped using this and went back to the PHP file method.
How did you implemented?
@juanjosezg I ended up using https://www.advancedcustomfields.com/resources/local-json/ . It's not automated (you have to press a sync button) but it's the best I could find that worked reliably.
@saminton Can you please provide a better link. The current is broken. Thanks
@Mulli, sorry I messed up the hyperlink. All fixed now.
acf_get_fields
@justinkmotion That worked. However all of my acf field groups got duplicated. How do i solve this?
@justinkmotion thanks to post the fix. Help me a lot.
Neither this nor @amjad's or @justinkmotion's solutions are working correctly for me when using flexible content and clones. It keeps randomly deleting acf fields.