Skip to content

Instantly share code, notes, and snippets.

@phpbits
Last active June 5, 2023 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phpbits/dc9a5061d50e22b50e4d3a57842275ec to your computer and use it in GitHub Desktop.
Save phpbits/dc9a5061d50e22b50e4d3a57842275ec to your computer and use it in GitHub Desktop.
/**
* 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