How to Create a Unique ID for Styling your WordPress Block

Real Snowflakes shot on a car window.
Snowflakes. License: Adobe Stock

Sometimes you need to style your blocks individually, and this is where a unique ID for each block can come in handy. So how do you get one?

Step 1: Add The 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.

Add the uniqueId attribute to your block's attributes
Sample Block.json With the uniqueId Attribute

Step 2: Add the useInstanceId hook to your block

Head to your block’s main block file (typically index.js or edit.js) and add in the useInstanceId hook:

import { useInstanceId } from '@wordpress/compose';
Two Variations of Including React Hook: useInstanceId

For the import variation, make sure compose is in your project’s dependencies.

For the alternate variation, include wp-element as part of your block script.

wp_register_script example
wp_register_script example

Step 3: Generate the Unique ID on Render

Generate a Unique ID
Generate a Unique ID

In the above example, I pass in a reference to my block and add a prefix of has-cts so the ids are: has-cts-0, has-cts-1

Step 4: Generate the unique ID using useEffect

Next up is updating the uniqueId attribute. We’ll want to update this each time as WordPress re-calculates unique values on each page refresh.

Using useEffect to set the uniqueId attribute
Using useEffect to set the uniqueId attribute

Step 5: Add the ID to Your Block Output

Adding a uniqueId to the block output in the id attribute
Add the uniqueId value to your block output

Step 6: Style Your Block

Example Style Output Code
Example Style Output Code

Step 7: Style the Frontend

The Frontend can use the uniqueId as well

That’s it!

Thanks for reading.

Like this tutorial? There's more like it. Subscribe today!

Name(Required)

Ronald Huereca
By: Ronald Huereca
Published On: on December 9, 2022

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.

Leave Your Valuable Feedback

Your email address will not be published. Required fields are marked *

Shopping Cart
  • Your cart is empty.
Scroll to Top