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;
    }
}

3 s
3

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.

Leave a Reply

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