Pass variables to an add_action hook [WordPress]

With global variables, unfortunately, you can not get very far and therefore it is necessary to use a separate function ...

  1. My use case

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){
		array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' )

My use case

In a blog post I showed you how i have all my Gutenberg blocks loaded automatically by WordPress at the same time.

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') ){
	}elseif (file_exists($block_path.'/block.js')) {

		add_action( 'enqueue_block_editor_assets', function() use ($slug){
				array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' )



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.


Gutenberg Javascript php Program technology Tips WordPress

Beitrag teilen

WhatsApp it

Folgen Sie uns