I programmed an add_action hook in WordPress today, where I gave a variable as a parameter to the anonymous function . I would like to show you how.
First of all, the code on how to pass variables to add_action hooks:
add_action( 'enqueue_block_editor_assets', function() use ($foo){
wp_enqueue_script(
$foo,
get_template_directory_uri().'/blocks/'.$foo.'/block.js',
array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' )
);
});
My use case
Now I did not even want to create a php file each time I programmed a block, so I was looking for a solution to load all javascript files at once. The solution looks like this:
foreach (glob(__DIR__ . '/*' , GLOB_ONLYDIR) as $block_path) {
$block_slug = str_replace(__DIR__.'/','',$block_path);
if( file_exists($block_path.'/'.$block_slug.'.php') ){
require_once($block_slug.'/'.$block_slug.'.php');
}elseif (file_exists($block_path.'/block.js')) {
add_action( 'enqueue_block_editor_assets', function() use ($slug){
wp_enqueue_script(
$slug,
get_template_directory_uri().'/blocks/'.$slug.'/block.js',
array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' )
);
});
wp_enqueue_style(
$block_slug.'-style',
get_template_directory_uri().'/blocks/'.$block_slug.'/'.$block_slug.'.css'
);
}
}
Thus I managed to reduce the need to only create a block in my dist folder and everything else is loaded fully automatically into WordPress.
I hope these tips helped you. I had to searched really long and therefore wanted to share this knowledge with you.