Random WordPress Function

Learn about a new WordPress function every day!


Function Signature:

wp_unique_term_slug

Function Description:

Makes term slug unique, if it isn't already.

Function Examples:

⚠️ Examples below are generated with GPT-3 once every hour. Do not take them too seriously.
Consider them as some extra input in your learning process - reason about them. Will it work? What could fail?
// Example 1: Generate a unique term slug for a new category
$term = 'New Category';
$taxonomy = 'category';
$parent = 0;
$unique_slug = wp_unique_term_slug(sanitize_title($term), (object) compact('term', 'taxonomy', 'parent'));
echo $unique_slug;
// Example 2: Ensure the uniqueness of a term slug within a specific taxonomy
$term = 'New Tag';
$taxonomy = 'post_tag';
$parent = 0;
$existing_term = get_term_by('name', $term, $taxonomy);
if ($existing_term) {
    $unique_slug = wp_unique_term_slug(sanitize_title($term), (object) compact('term', 'taxonomy', 'parent'));
} else {
    $unique_slug = sanitize_title($term);
}
echo $unique_slug;
// Example 3: Handle potential conflicts when updating an existing term
$term_id = 15;
$term = 'Updated Term Name';
$taxonomy = 'category';
$parent = 0;
$existing_term = get_term($term_id, $taxonomy);
if ($existing_term) {
    $unique_slug = wp_unique_term_slug(sanitize_title($term), (object) compact('term', 'taxonomy', 'parent'), $term_id);
} else {
    $unique_slug = sanitize_title($term);
}
echo $unique_slug;