Skip to content

Instantly share code, notes, and snippets.

@nikolailehbrink
Created June 6, 2023 14:34
Show Gist options
  • Save nikolailehbrink/08a5fa4349e41a361ee93b4f877ea87c to your computer and use it in GitHub Desktop.
Save nikolailehbrink/08a5fa4349e41a361ee93b4f877ea87c to your computer and use it in GitHub Desktop.
Automated ACF Blocks Registration: This script auto-registers ACF blocks from a specific WordPress directory.
/**
* This function is used to register Advanced Custom Fields (ACF) blocks
* from a specific directory. This can be useful when you have a lot of
* ACF blocks and want to keep your codebase clean and organized.
*
* This script assumes that each ACF block's code resides in its own folder under the
* /template-parts/blocks/ directory relative to where the script is located (__DIR__).
*/
function register_acf_blocks() {
// Define the directory path for the ACF blocks.
// __DIR__ is a magic constant in PHP that returns the path of the script that's being executed.
$dir = __DIR__ . '/template-parts/blocks/';
// scandir() returns an indexed array of files and directories from the directory.
// array_diff() is used to exclude the current (.) and parent directory (..) from the array.
$folders = array_diff(scandir($dir), array('..', '.'));
// Loop through the directories (ACF blocks)
foreach ($folders as $folder) {
// Check if the item is a directory and not a file using is_dir()
if (is_dir($dir . $folder)) {
// Register each ACF block to WordPress using register_block_type()
register_block_type($dir . $folder);
}
}
}
add_action('init', 'register_acf_blocks', 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment