Search code examples
phpwordpresswordpress-themingpermalinks

Random permalink key in wordpress


I want to have a custom permalink for each new post in WordPress like: http://mysite.com/x5Kvy6 (like bit.ly).

I tried this little script, but it adds only 5-digit numbers to the post title in the permalink.

function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {

if($slug!=""){
  $random=rand(11111,99999); //I needed 5 digit random
  $slug .= "-" . $random;
}
return $slug;

}

How can I make a random key instead of the post title?

I have not researched URL shorteners or redirection methods.

Any idea is welcome!


Solution

  • function wp_unique_post_slug($col,$table='wp_posts'){
         global $wpdb;
    
         $alphabet = array_merge( range(0, 9), range('a','z') );
    
         $already_exists = true;
         do {
    
             $guidchr = array();
             for ($i=0; $i<32; $i++)
             $guidchr[] = $alphabet[array_rand( $alphabet )];
    
    
             $guid = sprintf( "%s", implode("", array_slice($guidchr, 0, 12, true)) );
    
           // check that GUID is unique
           $already_exists = (boolean) $wpdb->get_var("
           SELECT COUNT($col) as the_amount FROM $table WHERE $col = '$guid'
           ");
    
          } while (true == $already_exists);
    
         return $guid;
    }
    

    This can be optimised in a number of ways.

    Also regarding this wp_unique_post_slug() -- yikes watch out for the name spacing. Wordpress already uses this function name