DEV Community

Jacob Bearce
Jacob Bearce

Posted on

Load ACF fields via PHP without losing importability

When working on custom WordPress themes, I almost always utilize the excellent plugin Advanced Custom Fields Pro. It makes creating custom fields incredibly easy for essentially any area of a site you can imagine, all via an intuitive GUI in the WordPress dashboard.

To ensure that your fields always load correctly, ACF allows you to export them as PHP for inclusion with your theme, or as JSON for importation in to another WordPress installation.

Loading in the fields via PHP is great because you can trust that your fields will always load as you designed them, but doing this prevents you from being able to import the fields back in to WordPress to make further edits in the future. Going the JSON route, you can easily import your fields back in to WordPress, but by leaving the fields in the back-end, you run the risk of a user accidentally modifying the fields, and breaking the theme.

After going back and forth on which method to rely on for my themes, I thought, "why not both?" Rather than rely on ACF's built-in PHP exportation feature, I realized I could export as JSON, then write my own PHP to load those fields in on the fly. Using this method, I'm able maintain one JSON copy of the fields, which can be imported to be edited, and then exported again without any modification to the PHP.

It's the best of both worlds, allowing maximum control over how fields get loaded while still maintaining the ability to import the fields to be edited via the GUI, without having to maintain two separate copies.

To load in the JSON fields that ACF exports, simply use the function below, pointing $acf_json_data to the location where your JSON is stored in your theme.

Top comments (0)