Rename class names in Gutenberg blocks
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
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