cafe_import_field_groups()
Purpose
Imports field group definitions from a CAFE export. It creates and/or updates groups and fields matched by their keys. It never deletes anything and never changes stored values. The same importer powers CAFE → Tools → Import. Guide: Tools.
Syntax
cafe_import_field_groups( array|string $data, string $mode = 'upsert' ): Cybo\AdvancedFieldEngine\Tools\ImportResult
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
$data |
string|array |
- | The JSON text of an export file, or the decoded document (as returned by cafe_export_field_groups()). |
$mode |
string | 'upsert' |
'create' creates missing groups and fields only. 'update' updates existing ones only. 'upsert' does both. |
Return value
An Cybo\AdvancedFieldEngine\Tools\ImportResult:
| Method | Returns |
|---|---|
is_successful() |
true when there were no errors (a file with nothing to change is a success too). |
has_changes() |
Whether anything was created or updated. |
errors() / warnings() |
Lists of code, message and path (e.g. groups[0].fields[2]). |
to_array() |
Everything, including created, updated and skipped groups and fields with reasons. |
Example
// Keep field groups in code: import the theme's file after it changes.
add_action( 'admin_init', function () {
$file = get_stylesheet_directory() . '/cafe-field-groups.json';
$hash = md5_file( $file );
if ( $hash === get_option( 'my_theme_cafe_hash' ) ) {
return;
}
$result = cafe_import_field_groups( file_get_contents( $file ), 'upsert' );
if ( $result->is_successful() ) {
update_option( 'my_theme_cafe_hash', $hash );
} else {
error_log( wp_json_encode( $result->errors() ) );
}
} );
Notes
- Everything is validated first. When anything is invalid, nothing is written.
- The writes run in one database transaction: a failure rolls everything back.
- Importing the same file twice changes nothing and creates no duplicates.
- A change that would make saved values unreadable (for example turning a text field with values into a number field) is refused.
- No capability check is made here (like
cafe_update_field()): checkcurrent_user_can()yourself when the file comes from a user. - Fires
cafe_field_groups_importedafter a successful import. - Preview first with
cafe_validate_field_group_import().