Hi quick question. I am trying to override the core/button html from within a theme that I am creating and I'm want to use the blocks.registerBlockType filter to alter the HTML for the block. Im stuck trying to figure out why the function overrideButtonBlock (in code below) isn't running.
Heres what my index.js looks like.
import { addFilter } from '@wordpress/hooks';
import Edit from './edit';
import Save from './save';
console.log('Loaded') // Outputs to the console;
const overrideButtonBlock = (settings, name) => { console.log('Attempting to override button block') // Never outputs to the console;
if (name !== 'core/button') {
return settings;
}
console.log('overrideButtonBlock function is running');
return {
...settings,
edit: Edit,
save: Save,
};
};
addFilter(
'blocks.registerBlockType',
'my-plugin/override-button-block',
overrideButtonBlock,
100
);
And my functions.php file
function enqueue_block_extensions() {
wp_enqueue_script(
'core-button-extension',
get_template_directory_uri() . '/js/build/blocks/buttons/index.js',
array( 'wp-blocks', 'wp-element', 'wp-i18n', 'wp-editor', 'wp-hooks', 'wp-dom-ready' ),
filemtime( get_template_directory() . '/js/build/blocks/buttons/index.js' ),
true
);
}
add_action( 'enqueue_block_editor_assets', 'enqueue_block_extensions', 20 );
Here’s the code to override the `core/button` block using the `blocks.registerBlockType` filter:
**index.js:**
“`javascript
import { addFilter } from ‘@wordpress/hooks’;
import Edit from ‘./edit’;
import Save from ‘./save’;
console.log(‘Loaded’); // Outputs to the console
const overrideButtonBlock = (settings, name) => {
if (name === ‘core/button’) {
console.log(‘overrideButtonBlock function is running’);
return {
…settings,
edit: Edit,
save: Save,
};
}
return settings;
};
addFilter(
‘blocks.registerBlockType’,
‘my-theme/override-button-block’,
overrideButtonBlock
);
“`
**functions.php:**
“`php
function enqueue_block_extensions() {
wp_enqueue_script(
‘core-button-extension’,
get_template_directory_uri() . ‘/js/build/blocks/buttons/index.js’,
array(‘wp-blocks’, ‘wp-element’, ‘wp-i18n’, ‘wp-editor’, ‘wp-hooks’, ‘wp-dom-ready’),
filemtime(get_template_directory() . ‘/js/build/blocks/buttons/index.js’),
true
);
}
add_action(‘enqueue_block_editor_assets’, ‘enqueue_block_extensions’, 20);
“`
This setup will load your custom `Edit` and `Save` components for the `core/button` block when you use the block editor.