I’ve created a custom WordPress block and would like to ensure that every time a block is newly generated or copied, it is assigned a unique ID. I’ve tried many approaches and have finally come up with the following solution:
= attributes.js
=
uniqueId: { type: String, default: '', },
= Excerpt from edit.js
=
const generateUniqueClass = () => { return `custom-${Math.random().toString(36).substr(2, 9)}`; }; useEffect(() => { const { uniqueClass } = attributes; if (!uniqueClass) { const newUniqueClass = generateUniqueClass(); setAttributes({ uniqueClass: newUniqueClass }); } else { const blocks = select('core/block-editor').getBlocks(); const isDuplicate = blocks.some( (block) => block.attributes.uniqueClass === uniqueClass && block.clientId !== clientId, ); if (isDuplicate) { const newUniqueClass = generateUniqueClass(); setAttributes({ uniqueClass: newUniqueClass }); } } }, [attributes.uniqueClass, clientId]);
Unfortunately, this solution doesn’t reliably work when I copy a block. Sometimes it works, sometimes it doesn’t—it’s currently like playing the lottery.
During my research, I also came across this hook:
// Apply filter addFilter( 'blocks.getSaveContent.extraProps', 'my-plugin/add-custom-class-on-copy', addCustomClassOnCopy );
Even here, I can’t get it to work.
Does anyone know of a better solution for my requirements?
In summary: When creating a WordPress block, a unique ID should be assigned and stored in an attribute called uniqueId. This ID should not change anymore. However, if a block is copied (and already has a unique ID), a new unique ID should be generated. Duplicate unique IDs must be avoided.