Skip to content

Instantly share code, notes, and snippets.

@poolghost
Created September 25, 2019 13:48
Show Gist options
  • Save poolghost/95aba8b92ed847ea44be65d4c042da0c to your computer and use it in GitHub Desktop.
Save poolghost/95aba8b92ed847ea44be65d4c042da0c to your computer and use it in GitHub Desktop.
Rename class names in Gutenberg blocks
const renameCoreBlocksDefaultClassNames = (className, blockName) => {
if (blockName === 'core/quote') {
return 'post__quote';
}
if (blockName === 'core/image') {
return 'post__figure';
}
return className;
};
const coreImageBlock = props => {
if (props.className.includes('wp-block-image')) {
props.className = props.className.replace('wp-block-image ', '')
}
if (typeof props.children.props === 'undefined') {
return props;
}
const children = props.children.props.children;
if (children[0]) {
Object.assign(children[0].props, {
className: `post__image ${children[0].props.className}`,
});
}
if (children[1]) {
Object.assign(children[1].props, {
className: 'post__figcaption',
});
}
return props;
}
const coreQuoteBlock = props => {
if (props.className.includes('wp-block-quote')) {
props.className = props.className.replace('wp-block-quote', '')
}
const children = props.children;
if (children[0]) {
const message = children[0];
message.props.value = message.props.value.replace(/<p>/gi, '<p class="post__quote__text">')
}
if (children[1]) {
Object.assign(children[1].props, {
className: 'post__quote__cite',
});
}
return props;
}
const classNamesForNestedElements = (props, blockType) => {
if (blockType.name === 'core/image') {
coreImageBlock(props);
}
if (blockType.name === 'core/quote') {
coreQuoteBlock(props);
}
return props;
};
wp.hooks.addFilter(
'blocks.getBlockDefaultClassName',
'your-namespace/block-filters',
renameCoreBlocksDefaultClassNames
);
wp.hooks.addFilter(
'blocks.getSaveContent.extraProps',
'your-namespace/block-filters',
classNamesForNestedElements
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment