How to generate random numeric slugs for a custom post type?

I have this PHP code to generate a random numeric string:

function generateRandomString($length = 12)
{
    global $generatedStrings;
    $characters="0123456789";
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    if (isset($generatedStrings[$randomString])) {
        $randomString = generateRandomString($length);
    }
    $generatedStrings[$randomString] = $randomString;
    return $randomString;
}

$generatedStrings = array();

foreach(range(1, 100000) as $num) {
    echo "\n".$num."\t : ".generateRandomString();
}

I was wondering if anyone could help figure out how to integrate this code with WordPress to auto-generate strings as slugs for a custom post type.

Any guidance you can provide is appreciated!

2 Answers
2

function wpse_18293_get_random_string ($number_of_chars_to_use)  {

    $upper_case_charachters = range('A', 'Z');

    while($cnt < $number_of_chars_to_use) {
        $random_string.= $upper_case_charachters[mt_rand(0,    count($upper_case_charachters)-1)];
        $cnt++;
    } 
    return $random_string
}

$random_string = wpse_18293_get_random_string('10');

The ’10’ can be any number, and the function will pass back a string of random charachters that many charachters long. Note, the function name can be anything you want, I named is as such to avoid function name conflicts.

what this does, is iterate $number_of_chars_to_use number of times, each loop it picks a random charachter from $uppser_case_charachters and adds it to a string. Voila, instant random charachter string.

It’s worth noting, the $upper_case_charachters is just an array filled with the alphabet. If you wanted numbers, you could easily swap range(‘0’, ‘9’);

Leave a Comment