Using the Interactivity API with Core Blocks #60479
Replies: 1 comment 1 reply
-
Yes, this is possible! You can use the WP_HTML_Tag_Processor together with the Interactivity API to accomplish this. Mind you that you'd have to use the brand-new WordPress 6.5 to be able to use the Interactivity API. Example which will log // some php file in your plugin
function my_custom_render( $block_content, $block ) {
if ( $block['blockName'] !== 'core/button' ) {
return $block_content;
}
// Enqueue the JS file.
// It assumes that the JS file is in the same directory as this PHP file
wp_enqueue_script_module(
'@my-plugin/entry',
plugin_dir_url( __FILE__ ) . 'index.js',
);
$p = new WP_HTML_Tag_Processor( $block_content );
$p->next_tag();
// Make sure that the namesspace you pass as parameter ("my-plugin/button-interactivity")
// matches the namespace of the store in the JS file.
$p->set_attribute( 'data-wp-interactive', 'my-plugin/button-interactivity' );
$p->set_attribute( 'data-wp-on--click', 'actions.logSomething' );
return $p->get_updated_html();
}
add_filter( 'render_block', 'my_custom_render', 10, 2 ); And your JS file in the same folder as the PHP file: import { store } from '@wordpress/interactivity';
store("my-plugin/button-interactivity", {
actions: {
logSomething() {
console.log('hello');
}
},
}); This example will work but the team working on the Interactivity API is thinking about ways to make this kind of use case even easier! There have been some explorations around "Behaviors UI" (#50029) where the end goal is very similar to your use case but more general: Being able to assign custom "behaviors" to common UI elements. That work has been paused for now as the initial approach was not adequate but I hope that it can resume in the not so far future! |
Beta Was this translation helpful? Give feedback.
-
I'm wondering if it's possible currently to use the Interactivity API in conjunction with core blocks.
As an example is there a way for me to use the core/button block and have it mutate the state of custom block (using the interactivity api)?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions