Adding JS to your ACF Block with block.json


Adding JavaScript to your Advanced Custom Fields (ACF) block in WordPress can really enhance the functionality and interactivity of your custom blocks. Here’s a good way to do it, keeping things clean and maintainable:

  1. Setup a directory to hold all your blocks in, then loop through them to register each automatically.
// I put the blocks directory in the root of the theme directory.
// glob(__DIR__ . '/../blocks/josh-*') will get all directories in our blocks folder that start with josh-.
// Each of these directories is assumed to be a block, and register_block_type is called for each one.
function josh_register_acf_blocks() {
	foreach ( glob( __DIR__ . '/blocks/josh-*' ) as $block_path ) {
		register_block_type( $block_path );
	}
}

add_action( 'init', 'josh_register_acf_blocks' );

2. Now loop through each block and enqueue the JavaScript files.

function josh_register_acf_blocks() {
	foreach ( glob( __DIR__ . '/blocks/josh-*' ) as $block_path ) {
		register_block_type( $block_path );
	}
	// Register js files in block directories
	// You'll have to name your js file "josh-my-block-name.js" so that it adds the right name space for the block.
	foreach ( glob(__DIR__ . '/blocks/josh-*/*.js') as $path) {
		$file_name = pathinfo($path, PATHINFO_FILENAME);
		wp_register_script( $file_name, get_stylesheet_directory_uri() . '/blocks/' . $file_name . '/' . $file_name . '.js', '', $GLOBALS['version']);
	}
}

add_action( 'init', 'josh_register_acf_blocks' );

3. Now in your block.json you can reference the enqueued file with the namespace.

{
    "name": "josh/josh-info-card",
    "title": "Josh Info Card",
    "description": "A row of 3 cards that have an icon/logo, a title, a description, and a link.",
    "script": [ "jquery","josh-info-card" ],
    //... the rest of your settings ... //
}