Give each term in a given taxonomy a unique alphanumeric ID

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).

<?php
function invman_generate_location_tag( $term_id, $term_tax_id ) {
$existing_tag = get_term_meta( $term_id, 'invman_location_tag' );
if ( $existing_tag ) {
return;
}
$characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
$characters_length = strlen( $characters );
$random_string = 'B';
for ( $i = 0; $i < 3; $i++ ) {
$random_string .= $characters [ wp_rand( 0, $characters_length – 1 ) ];
}
/**
* Now check if this tag already exists
*/
$existing_tags = get_terms(
array(
'taxonomy' => 'inventory_location',
'meta_key' => 'invman_location_tag',
'meta_value' => $random_string,
)
);
if ( $existing_tags ) {
return invman_generate_location_tag( $term_id, $term_tax_id );
} else {
add_term_meta( $term_id, 'invman_location_tag', $random_string );
return $random_string;
}
}
add_action( 'edited_inventory_location', 'invman_generate_location_tag', 10, 2 );
add_action( 'created_inventory_location', 'invman_generate_location_tag', 10, 2 );
view raw gistfile1.php hosted with ❤ by GitHub

By Dave

Dave is the proud father of Ellie and Jack. There's nothing that makes him happier than spending time with his incredible wife and their amazing children. He's a civil/mechanical engineer and he also builds and maintains WordPress websites.

Leave a Reply