I had a problem recently where I wanted to create a custom taxonomy and I wanted each term created within that custom taxonomy to have a unique ID, to use in the real world.
The use case in my scenario is that I wanted to create unique tags for storage boxes. I created a new taxonomy (inventory_location
) and started adding my storage boxes.
I wanted the IDs to be of a particular format. Firstly, they had to start with the letter B (for box). Secondly, they needed 3 alphanumeric characters after that to create a unique identifier for each box. I excluded the letters O and I, and the number 1 and 0 to avoid confusion. Using only uppercase letters, this gave me a list of 32 characters to work with, giving me a maximum of 32^3 (32,768) combinations for my storage box tags (more than enough!).
I hooked into edited_{$taxonomy) and created_{$taxonomy} to ensure that each term had a unique tag whenever a term was created or edited.
In the snippet below, in lines 4-7, I check to see if the term already has a tag, and bail if we do.
In lines 9-14, I create a random tag based on my specifications outlined above.
In lines 19-25, I check whether an existing term already has this meta value and then either try again if the meta value already exists (lines 27-28), or set the meta value for the created/edited term (lines 30-31).