Home Forums ACF PRO Generate random code Reply To: Generate random code

  • I’ve done similar using the below code:

    add_action( 'transition_post_status', 'generate_random_url', 10, 3 );
    function generate_random_url( $new_status, $old_status, $post ) {
        #only apply this to a particular post type 	
    	if ( 'publish' !== $new_status or 'publish' === $old_status || 'cpt' !== get_post_type( $post ) )
    	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
            ####generate the random slug
            #get current date/time
            $date = date('YmdH:i:s');
            $randomise = ($date * 25);
            #hash the randomised value, just adds another level but doesn't need to be 100% secure
            $new_slug = md5($randomise);
            #get the post data
            $my_post = array(
                'ID'        => $post->ID,
                'post_name'    => $new_slug
            #update the post into the database
            wp_update_post( $my_post );
    		#update the download ID field
    		update_post_meta( $post->ID, 'download_id', $new_slug );

    Basically, once the custom post type was saved, it would generate a random value based on a date time stamp.
    I used this to create a random page URL but you can see it also updated a custom field called download ID

    I’m sure there are other ways to do this but should get you underway.