• Resolved wizzy85

    (@wizzy85)


    Hi all!
    I have written this plugin for a sport club where you can book tennis courts; the idea is to give the admin the possibility to “manual add” new booking.
    To do that I created a custom post type called “booking”, when the admin will click on “add new” I’d like to see the “title box” of my cpt auto-filled with a unique code or incremental id that will identify that booking.
    Which is the best way to generate a title/code like that?
    If I have two people logged with the same admin credentials will be there collapse problem in the code generation?

    function change_mycpt_default_title() {
        if( $_GET['post_type'] == 'booking' ) {
            return 'UNIQUE CODE HERE';
        }
    }
    
    add_filter('default_title', 'change_mycpt_default_title');

    This is the code I use to change the default title of my cpt.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The best way to generate a unique ID using PHP is to use the uniqid() function. If you read through that page you’ll see that it should give you one of the more unique values that you can get.

    Another option is to use the post ID, as there should be a new post objet by that stage, and use that. something like this (not tested, but should work if I’m right)…

    global $post;
    return 'Booking No. '.$post->ID;
    Thread Starter wizzy85

    (@wizzy85)

    Ok! Here the working code:

    function change_mycpt_default_title( $post_title, $post ) {
        if( 'booking' == $_GET['post_type'] ) {
            $post_title = 'My custom code ' . $post->ID;
        }
    
        return $post_title;
    }
    
    add_filter( 'default_title', 'change_mycpt_default_title', 10, 2 );

    For some reason it only shows the [post ID] and not [‘My custom code’ + the post ID]… but I can live with that !

    Thanks for posting the working code !

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Auto-generate unique code/id as title’ is closed to new replies.