My previous tutorial focused on creating a unique ID for your WordPress block at runtime. However, this ID isn’t permanent.
Within this tutorial, I’ll show you how to create a permanent unique ID that also works with block duplication.
Step 1: Add a uniqueId attribute
Head to your block’s block.json file and add in the uniqueId
attribute. Give it a type of string with an empty default.
Step 2: Add a uniqueIds array above your component
In your block’s block code, add a const
of uniqueIds
above your component.
This variable is important because we need to keep track of all of our block IDs globally so that we can generate a new ID in the event the block is duplicated.
// For storing unique IDs.
const uniqueIds = [];
Code language: JavaScript (javascript)
Step 3: Grab the block’s clientId
The block’s clientId
is a unique string passed to each block at runtime and at block generation. This ID always changes, but you can use it to generate a unique ID for your block.
Step 4: Grab the uniqueId attribute
Grab the uniqueId attribute. We’re going to need it later.
const {
uniqueId,
} = attributes;
Code language: JavaScript (javascript)
Step 5: Add a useEffect to set the uniqueId
We’ll use useEffect
to set the uniqueId if it doesn’t exist. If the uniqueId
already exists in our array variable uniqueIds
(note the plurality), then a new ID is generated.
/**
* Get a unique ID for the block for inline styling if necessary.
*/
useEffect( () => {
if ( ( null === uniqueId || '' === uniqueId ) || uniqueIds.includes( uniqueId ) ) {
const newUniqueId = 'wppic-' + clientId.substr( 2, 9 ).replace( '-', '' );
setAttributes( { uniqueId: newUniqueId } );
uniqueIds.push( newUniqueId );
} else {
uniqueIds.push( uniqueId );
}
}, [] );
Code language: JavaScript (javascript)
This code does the following:
- Looks for the
uniqueId
attribute. If it’s blank or is stored inuniqueIds
, then a new ID is generated. - Generates the
newUniqueId
based on theclientId
and a prefix. - Updates the
uniqueId
attribute and pushes touniqueIds
array for storage. - If the
uniqueId
is already set, add to theuniqueIds
array for storage.
So at first render, a new ID is generated, is checked against existing IDs, and a unique ID is generated.
In the event of block duplication, the uniqueId
would have already been added to the uniqueIds
array, so a duplicate would be found, and a new unique ID is generated.
Step 6: Add the ID to Your Block Output
Step 7: Style Your Block
Step 8: Style the Frontend
That’s it!
Please comment below if you have any questions.
Like this tutorial? There's more like it. Subscribe today!
Ronald Huereca founded DLX Plugins in 2022 with the goal of providing deluxe plugins available for download. Find out more about DLX Plugins, check out some tutorials, and check out our plugins.