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!
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
if($slug!=""){
$random=rand(11111,99999); //I needed 5 digit random
$slug = $random;
}
.= is for concat of strings.
The correct way to use Mwayi answer is using the filter wp_unique_post_slug
, as function wp_unique_post_slug()
will conflit with WP own function. Inside WP function we find this filter hook.
add_filter( 'wp_unique_post_slug', 'unique_slug_so_11762070', 10, 6 );
function unique_slug_so_11762070( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
$new_slug = so_11762070_unique_post_slug('guid');
return $new_slug;
}
# From: https://stackoverflow.com/a/11762698
function so_11762070_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;
}
For SEO, you better keep the slug as meaningful as possible, ie. do not change the permalink to a random sequence.
Using This plugin, you still can use http://example.com/raNd0m permalink for sharing purposes in social networks or images from your site.
This way you win both SEO and shortlinks
I used http://ijassar.info/underrated to write a post about this specific subject