Last active
May 17, 2024 03:12
-
-
Save mennwebs/e61ba9593440060dd9148fe75049af44 to your computer and use it in GitHub Desktop.
WordPress - Random Slug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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