How to automatically generate a unique random slug

I have tried to create a function that generates a random slug when a post is created. I am a bit worried that the function generates non unique strings as slugs. How can I solve this?

The function looks like:

add_filter('name_save_pre','unique_slug', 0);

function random_string() {
    $length = 6;
    $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
    $string = '';    
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}

function unique_id($slug) {
    global $wpdb;

    return $wpdb -> get_row("SELECT ID FROM wp_post WHERE post_name = '" . $slug . "' && post_status = 'publish' && post_type = 'post'");   
}

function unique_slug($slug) {
    if($slug) return $slug;

    $random_slug = random_string();
    if(!unique_id($random_slug)){
        //what to do here?
    }
    else {
        return $random_slug;
    }
}

Related posts

Leave a Reply

3 comments

  1. Use the function wp_unique_post_slug(). Do not reinvent the wheel, this one is quite tricky.

    Usage:

    $unique_slug = wp_unique_post_slug( 
        $slug,
        $post_ID, 
        $post_status,
        $post_type, 
        $post_parent 
    );
    

    Then you can test if $slug === $unique_slug and generate a new one if the test fails.

    You can find the function in wp-includes/post.php. It ends with a filter 'wp_unique_post_slug', so you can still adjust the return value if you don’t like it.

  2. This is how a unique random slug can be generated.

    function randomSlug() {
        $length = 5;
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $slug = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= substr( $chars, wp_rand( 0, strlen($chars) - 1 ), 1 );
        }
        return $slug;
    }
    
    function slugExists($slug) {
        global $wpdb;
        if($wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE post_name = '$slug'")) {
            return true;
        } else {
            return false;
        }
    }
    
    function uniqueRandomSlug() {
        do {
            $randomSlug = randomSlug();
            $slugExists = slugExists($randomSlug);
        } while ( $slugExists );
    
        return $randomSlug;
    }