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;
}
}
Use the function
wp_unique_post_slug()
. Do not reinvent the wheel, this one is quite tricky.Usage:
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.I’ve found this plugin that should do the trick: http://wordpress.org/extend/plugins/wp-hashed-ids/
This is how a unique random slug can be generated.