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!

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');

  • Thank you, @hybrid-web-dev! Much appreciated! Would try it right way, but I'm not sure if this code is a function that should be included in functions.php?! If so, how do I assign this code to work on one custom post type only? Kind regards, rey – rey Nov 30 '14 at 11:28
  • I'll modify my answer. – Hybrid Web Dev Nov 30 '14 at 19:51
  • Hi @hybrid-web-dev. I get a blank page when I put this code in functions.php :( – rey Nov 30 '14 at 22:46
  • Forgot to add a ; at the end of the $random_string = wpse_18293_get_random_string('10'); – Hybrid Web Dev Nov 30 '14 at 23:27
  • Added a ; at the end of return $random_string, too. Not getting a blank page anymore :). But how do I add this to one custom post type only instead of globally? For example, the 'image' post type. So I'd generate urls like mysite.com/image/948593839215 – rey Nov 30 '14 at 23:35

Here's an example how you can auto generate numeric slugs, other than the post IDs:

/**
 * Auto generate numeric slugs for a given custom post type (via post.php screen)
 * Requires PHP 5.3+
 * @see http://wordpress.stackexchange.com/a/169907/26350
 */
add_action( 'load-post.php', function(){
    add_filter( 'wp_insert_post_data', function( $data, $postarr ) {
        if(
            'post' === $data['post_type']   // <-- Edit the cpt to your needs!
            && empty( $data['post_name'] )
            && isset( $postarr['post_ID'] )
            && $postarr['post_ID'] * 1 > 0
        )
        {
            //----------------------------------
            // Method with post ID reference (not random):
            //
            $data['post_name'] = sprintf( '%u', crc32( $postarr['post_ID'] ) );

            //----------------------------------
            // Method without post ID reference (random):
            //                 
            // $data['post_name'] = rand( 10000000, 99999999 );        
        }
        return $data;
    }, 10, 2 );
});

where you can modify the post type to your needs.

This will kick in on the post.php screen and not the post-new.php screen.

You can easily test the collisions of the crc32() PHP function, for post ID from 1 to 100.000, using the script in this answer. I tested it up to one million without any collisions.

Notice that if the unlikely thing will happen, that you generate a previous existing slug, then WordPress will take care of it as usual via the wp_unique_post_slug() function.

Hopefully you can adjust this further to your needs.

  • Hi @birgire! Unfortunately the code didn't work :( I suppose to replace only 'post_type', correct? And put it in the theme's functions.php, correct? – rey Nov 30 '14 at 17:53
  • Hi @rey, yes just change the 'post' value to your needs. This should work from functions.php. Must the slugs be numeric only or can it be alpha-numeric? – birgire Nov 30 '14 at 18:47
  • Numeric only ;) To generate urls like, for example: designspiration.net/image/411126849521/ – rey Nov 30 '14 at 22:35
  • Ah, I was replacing the wrong thing! Sorry, my bad, it works now!! Many thanks @birgire! :) If I want a longer length, I just need to add zero's and nine's, correct? – rey Nov 30 '14 at 23:28
  • ok great, yes you could increase the 0's and 9's. I updated the answer with a restriction to the post.php screen and I added a crc32() example. – birgire Dec 1 '14 at 2:56

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.