Home › Forums › ACF PRO › Generate random code › Reply To: Generate random code
I’ve done similar using the below code:
<?php
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 ) )
return;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
####generate the random slug
#get current date/time
$date = date('YmdH:i:s');
#randmoise
$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.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.