-
-
Save JacobDB/a18b316eeb822aeaf7b25b3cc75d982c to your computer and use it in GitHub Desktop.
<?php | |
/** | |
* Read ACF fields from JSON | |
*/ | |
function PREFIX_acf_register_json_fields() { | |
if (function_exists("acf_add_local_field_group")) { | |
$acf_json_data = locate_template("path/to/advanced-custom-fields.json"); | |
$custom_fields = $acf_json_data ? json_decode(file_get_contents($acf_json_data), true) : array(); | |
foreach ($custom_fields as $custom_field) { | |
acf_add_local_field_group($custom_field); | |
} | |
} | |
} | |
add_action("init", "PREFIX_acf_register_json_fields"); |
any suggestions if this isn't working for me?
I verified that my $acf_json_data is pointing to the correct location, but nothing is loading for those fields.
I also tried removing the fields from ACF altogether to make sure there wasn't some conflict making them not load.
any suggestions would be greatly appreciated.
@joshespi I just tested this, and it seems to be working correctly for me with the latest versions of WordPress and ACF Pro. The below code will add a text field called "Test" to all posts in the post
post type.
Here's my PHP, in functions.php:
/**
* Read ACF fields from JSON
*/
function PREFIX_acf_register_json_fields() {
if (function_exists("acf_add_local_field_group")) {
$acf_json_data = get_theme_file_path("acf-export-2023-04-12.json");
$custom_fields = $acf_json_data ? json_decode(file_get_contents($acf_json_data), true) : array();
foreach ($custom_fields as $custom_field) {
acf_add_local_field_group($custom_field);
}
}
}
add_action("init", "PREFIX_acf_register_json_fields");
And here's my export file, in the root of the theme, named acf-export-2023-04-12.json:
[
{
"key": "group_6436dd39db816",
"title": "Test",
"fields": [
{
"key": "field_6436dd3ab6565",
"label": "Test",
"name": "test",
"aria-label": "",
"type": "text",
"instructions": "",
"required": 0,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"relevanssi_exclude": 0,
"default_value": "",
"maxlength": "",
"placeholder": "",
"prepend": "",
"append": ""
}
],
"location": [
[
{
"param": "post_type",
"operator": "==",
"value": "post"
}
]
],
"menu_order": 0,
"position": "normal",
"style": "default",
"label_placement": "top",
"instruction_placement": "label",
"hide_on_screen": "",
"active": true,
"description": "",
"show_in_rest": 0
}
]
thanks for the quick reply!
I figured out my issue. I was trying to put the function to load the json in a plugin rather than my functions.php file.
moving things made it work as you described. Thanks for helping me work through that!
For anyone looking to do the same thing, except make the fields editable, change
acf_add_local_field_group
toacf_import_field_group
.