Last active
July 24, 2024 18:10
-
-
Save noahduncan/bb658cf8a7c7947af7ea0b00b173686f to your computer and use it in GitHub Desktop.
Automatically Sync ACF Fields on dev environments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Zing ACF Auto Sync | |
Plugin URI: | |
Description: Plugin that automatically syncs the database with local json for .test urls | |
Version: 20180419 | |
Author: Noah Duncan <[email protected]> | |
*/ | |
/* Put in /wp-content/mu-plugins/zing-acf-auto-sync/zing-acf-auto-sync.php if you want as a plugin */ | |
/** | |
* Function that will update ACF fields via JSON file update. | |
* It would be better to hook into ACF's own update function...but | |
* this works for now. | |
*/ | |
function zing_sync_acf_fields() { | |
error_log('syncing 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 ] ); | |
} | |
} | |
} | |
if (preg_match('/\.(test|dev)$/', $_SERVER['HTTP_HOST'])) { | |
add_action( 'admin_init', 'zing_sync_acf_fields' ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment