Skip to content

Instantly share code, notes, and snippets.

@mishterk
Last active Dec 30, 2020
Embed
What would you like to do?
Dynamically set the ACF JSON directory so that each sub-site in a WordPress multisite network has a separate acf-json dir. This maximises compatibility with ACF Custom Database Tables.

Using ACF JSON on WordPress multisite installations

ACF JSON can get a little messy where you need different field groups across your sub-sites. If you are using separate themes or separate child themes for each sub-site, you'll be fine as long as each theme/child-theme has its own /acf-json directory.

If, however, you want to enforce unique acf-json directories for each sub-site, you can do so using one of the following snippets.

  1. Dynamic ACF JSON directory
    This will simply define the location of the directory within the sub-site's uploads/sites/{subsite} directory but it won't create the directory for you. All you need to do in this case is create the uploads/sites/{subsite}/acf-json directory to ensure this functions.
  2. Dynamic ACF JSON directory with directory creation
    This is the same as above except that it checks for the existence of the directory and creates it if it doesn't exist. This should be fine but if you want to squeeze as much peformance out of your site as possible, manually creating the snippet is a little bit better as there is no checking for the directory each time the app runs.

Where to put it?

The snippet can be added to your theme files but if you are using ACF Custom Database Tables, you'll run into some issues as the CDT plugin needs to load early and needs early access to ACF's JSON directory settings. With that in mind, the snippet is best placed in an mu-plugin which can't be deactivated and will run across the whole network of sites.

<?php
add_filter( 'acf/settings/save_json', function ( $path ) {
return trailingslashit( wp_upload_dir()['basedir'] ) . 'acf-json';
} );
add_filter( 'acf/settings/load_json', function ( $paths ) {
return [
trailingslashit( wp_upload_dir()['basedir'] ) . 'acf-json'
];
} );
<?php
add_filter( 'acf/settings/save_json', function ( $path ) {
$dir = trailingslashit( wp_upload_dir()['basedir'] ) . 'acf-json';
// If you want to force creation if/when the directory doesn't exist,
// this is one way to handle it:
if ( ! file_exists( $dir ) ) {
wp_mkdir_p( $dir );
}
return $dir;
} );
add_filter( 'acf/settings/load_json', function ( $paths ) {
return [
trailingslashit( wp_upload_dir()['basedir'] ) . 'acf-json'
];
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment