php – Long WordPress Random Unique Slug Generator

Question

I am looking to create a long random url slug. This is the solution I have adopted, but my site contains 10,000 pages and I was wondering if it will take a lot of time to perform or if there is a better solution for this task.

Also I am wondering if I really need slugExists function, since the probability of the same long random url existing on my site is almost zero ?

 function randomSlug() {
        $length = 25;
        $chars="abcdefghijklmnopqrstuvwxyz0123456789";
        $slug = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= substr( $chars, wp_rand( 0, strlen($chars) - 1 ), 1 );
        }
        return $slug;
    }
    
    function slugExists($slug) {
        global $wpdb;
        if($wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE post_name="$slug"")) {
            return true;
        } else {
            return false;
        }
    }
    
    function uniqueRandomSlug() {
        do {
            $randomSlug = randomSlug();
            $slugExists = slugExists($randomSlug);
        } while ( $slugExists );
    
        return $randomSlug;
    }

0
JoaMika 2 months 2022-10-07T05:29:25-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse