Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save athaller/085ab0e9b1ffa948cdd8673a34ce8553 to your computer and use it in GitHub Desktop.
Save athaller/085ab0e9b1ffa948cdd8673a34ce8553 to your computer and use it in GitHub Desktop.
<?php
namespace DeliciousBrains\Admin;
use DeliciousBrains\DBI;
class ACF {
public function init() {
add_filter( 'acf/settings/save_json', array( $this, 'get_local_json_path' ) );
add_filter( 'acf/settings/load_json', array( $this, 'add_local_json_path' ) );
if ( ! WP_LOCAL_DEV ) {
// Only allow fields to be edited on development
add_filter( 'acf/settings/show_admin', '__return_false' );
}
add_action( 'admin_init', array( $this, 'sync_fields_with_json' ) );
}
/**
* Define where the local JSON is saved
*
* @return string
*/
public function get_local_json_path() {
return DBI::get_data_dir() . 'acf-json';
}
/**
* Add our path for the local JSON
*
* @param array $paths
*
* @return array
*/
public function add_local_json_path( $paths ) {
$paths[] = DBI::get_data_dir() . 'acf-json';
return $paths;
}
/**
* Automatically sync any JSON field configuration.
*/
public function sync_fields_with_json() {
if ( defined( 'DOING_AJAX' ) || defined( 'DOING_CRON' ) ) {
return;
}
if ( ! function_exists( 'acf_get_field_groups' ) ) {
return;
}
$groups = acf_get_field_groups();
if ( empty( $groups ) ) {
return;
}
$sync = array();
foreach ( $groups as $group ) {
$local = acf_maybe_get( $group, 'local', false );
$modified = acf_maybe_get( $group, 'modified', 0 );
$private = acf_maybe_get( $group, 'private', false );
if ( $local !== 'json' || $private ) {
// ignore DB / PHP / private field groups
continue;
}
if ( ! $group['ID'] ) {
$sync[ $group['key'] ] = $group;
} elseif ( $modified && $modified > get_post_modified_time( 'U', true, $group['ID'], true ) ) {
$sync[ $group['key'] ] = $group;
}
}
if ( empty( $sync ) ) {
return;
}
foreach ( $sync as $key => $v ) {
if ( acf_have_local_fields( $key ) ) {
$sync[ $key ]['fields'] = acf_get_local_fields( $key );
}
acf_import_field_group( $sync[ $key ] );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment