Skip to content

Instantly share code, notes, and snippets.

@mennwebs
Last active May 17, 2024 03:12
Show Gist options
  • Save mennwebs/e61ba9593440060dd9148fe75049af44 to your computer and use it in GitHub Desktop.
Save mennwebs/e61ba9593440060dd9148fe75049af44 to your computer and use it in GitHub Desktop.
WordPress - Random Slug
<?php
add_filter('wp_unique_post_slug', 'seed_unique_slug', 10, 4);
function seed_unique_slug($slug, $post_id, $post_status, $post_type)
{
if (in_array($post_type, ['post', 'product'])) {
$post = get_post($post_id);
if (empty($post->post_name) || $slug != $post->post_name) {
$slug = randomSlug();
}
}
return $slug;
}
function randomSlug()
{
$length = 5;
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$slug = '';
for ($i = 0; $i < $length; $i++) {
$slug .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
}
return $slug;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment