Last active
June 5, 2023 17:05
-
-
Save phpbits/dc9a5061d50e22b50e4d3a57842275ec to your computer and use it in GitHub Desktop.
Extend Existing Block with Custom Block Toolbar Control https://jeffreycarandang.com/how-to-create-and-extend-block-toolbar-controls-on-wordpress-gutenberg-block-editor/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add Custom Block Control to Existing Block | |
*/ | |
import Controls from './controls'; | |
const { createHigherOrderComponent } = wp.compose; | |
const { Fragment } = wp.element; | |
const allowedBlocks = ['core/group']; // Enable control to existing Group block | |
/** | |
* Add custom attribute | |
*/ | |
function addAttributes(settings) { | |
// Check if attributes exists and compare the block name | |
if (typeof settings.attributes !== 'undefined' && allowedBlocks.includes(settings.name)) { | |
settings.attributes = Object.assign(settings.attributes, { | |
theme: { | |
type: 'string', | |
default: '', | |
}, | |
}); | |
} | |
return settings; | |
} | |
wp.hooks.addFilter('blocks.registerBlockType', 'example/add-atttibutes', addAttributes); | |
/** | |
* Add Custom Block Controls | |
*/ | |
const addBlockControls = createHigherOrderComponent((BlockEdit) => { | |
return (props) => { | |
const { name, isSelected } = props; | |
if (!allowedBlocks.includes(name)) { | |
return <BlockEdit {...props} />; | |
} | |
return ( | |
<Fragment> | |
{isSelected && <Controls {...props} />} | |
<BlockEdit {...props} /> | |
</Fragment> | |
); | |
}; | |
}, 'addBlockControls'); | |
wp.hooks.addFilter('editor.BlockEdit', 'example/add-block-controls', addBlockControls); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment