How to get Advanced Custom Fields to load JSON files from more than one directory

If you use Advanced Custom Fields a lot you are probably using ACF’s very awesome Local JSON feature.

By default, ACF saves and loads all JSON files from the acf-json directory inside your theme but it is possible to take control of ACF’s behaviour to define your own custom load points as outlined in the Advanced Custom Fields documentation.

By adding your own directories, you are able to define many points within your app that can’t be easily overridden by people working with the custom fields in the WordPress admin. Being able to load from many directories also makes it possible for you to bundle your field groups into component-based directories which you could use to build and maintain a library of portable UI components…ooh-la-la!

How to register your own ACF JSON load points

<?php
add_filter( 'acf/settings/load_json', function ( array $directories ) {
// Define as many directories as necessary. ACF will look in each
// directory and load any JSON files it finds.
$directories[] = get_stylesheet_directory() . '/components/one';
$directories[] = get_stylesheet_directory() . '/components/two';
$directories[] = get_stylesheet_directory() . '/components/three';
return $directories;
} );

As you can see from the above snippet, it’s super easy to define your own ACF JSON load directories.

Auto registering all subdirectories as ACF JSON load points

Let’s say you have a components directory which contains multiple directories, each representing a component, and each of these components contain their own ACF JSON files. An easy way to handle loading JSON files from each would be to simply read the directory with PHP and register each subdirectory:

<?php
add_filter( 'acf/settings/load_json', function ( array $directories ) {
$base_dir = get_stylesheet_directory() . '/components';
$resource = opendir( $base_dir );
while ( ( $file = readdir( $resource ) ) !== false ) {
// Skip current and parent directory references
if ( in_array( $file, array( '.', '..' ), true ) ) {
continue;
}
// Get the full path
$dir = "$base_dir/$file";
// If we have a directory (not a file) add it to our ACF JSON load paths
if ( is_dir( $dir ) ) {
$directories[] = $dir;
}
}
closedir( $resource );
return $directories;
} );

Need a website? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.