I need random (and unique) alphanumeric permalinks. I’ve looked at several plugins but they all seem to do some form of redirection to a longer URL. That’s not what I want, I want the permalink to be changed.
Basically, I’m wanting URLs like bit.ly or 9gag.com.
I’ve looked, but came up empty in my searches – does a plugin exist that does this? If not, could someone point me into the right direction as to how I might accomplish it? I’m pretty self sufficient in PHP but I’m not very familiar with WordPress yet.
The easiest way I could think of is something like add_filter("post_slug", md5(rand()))
(if that were actually valid code). Obviously, I’d have to check for duplicate slugs and what not…
Honestly, what I’d much rather prefer is something like:
example.com/prefix/hf434g5ay/postname
In that the /prefix/alphanumeric-key
is required but postname is used for SEO.
2 Answers
If you’d like to keep your slugs for SEO, then you’ll want to define a new rewrite tag and leave the default behavior for post slugs.
If you’d like a unique id, then instead of looking up possible duplicates, why not just re-use the post ID which is guaranteed to be unique given a MySQL primary index – you can convert it to a base36 number if you want it to look more like bitly.
add_action( 'init', function() {
add_rewrite_tag( '%my_id%', '([a-z0-9]+)' );
});
add_action( 'pre_get_posts', function( $query ) {
if ( ! $query->is_main_query() || is_admin() )
return;
$id = $query->get( 'my_id' );
if ( ! empty( $id ) ) {
$query->set( 'p', base_convert( $id, 36, 10 ) );
$query->set( 'name', null );
}
});
add_filter( 'post_link', function( $permalink, $post ) {
$id = base_convert( $post->ID, 10, 36 );
return str_replace( '%my_id%', $id, $permalink );
}, 10, 2 );
Then change your permalinks structure to /%my_id%/%postname%/
in Settings – Permalinks. If you want more than 0-9 and lowercase characters, you can look for some base 62 implementations, though I’m not a big fan of case-sensitive URLs.
Hope that helps.