Skip to content

Instantly share code, notes, and snippets.

@bacoords
Created May 16, 2023 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bacoords/986029d783edf320ce93455e0f6b5dd6 to your computer and use it in GitHub Desktop.
Save bacoords/986029d783edf320ce93455e0f6b5dd6 to your computer and use it in GitHub Desktop.
Import exported ACF Field Groups on plugin activation
<?php
/**
* Helper function to import the ACF field group if it doesn't exist.
*
* @return void
*/
function example_import_acf_field_group() {
if ( function_exists( 'acf_import_field_group' ) ) {
// Get all json files from the /acf-field-groups directory in your plugin.
$files = glob( plugin_dir_path( __FILE__ ) . '/acf-field-groups/*.json' );
// If no files, bail.
if ( ! $files ) {
return;
}
// Loop through each file.
foreach ( $files as $file ) {
// Grab the JSON file.
$group = file_get_contents( $file );
// Decode the JSON.
$group = json_decode( $group, true );
// If not empty, import it.
if ( is_array( $group ) && ! empty( $group ) && ! acf_get_field_group( $group[0]['key'] ) ) {
acf_import_field_group( $group [0] );
}
}
}
}
register_activation_hook( __FILE__, 'example_import_acf_field_group' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment