Adding a random string as slug för CPT
-
Hi!
I’m trying to add a random string as slug for a CPT. I’m not a programmer so my solution after googling a lot is to first add a new custom field called cv_random_string and creating a random string that i fill it with. Then I use the value of that field and use it as slug. This works fine when creating the post. But when I update the post the random string is added once again to the slug. This only happens once. https://www.mysite.com/cv/v6ji4puptusr becomes https://www.mysite.com/cv/v6ji4puptusr-v6ji4puptusr/.
I would like it to only have the random string appended to the slug once. Also, maybe it’s possible to not use my two step solution with the random string field? 🙂
What I want is basically to add a random string as slug in the CPT cv.
This is the code I use:
/** Generate random string */ function wpwebguider_random_string( $length = 12 ) { $str = ""; $characters = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z')); // $characters = range('A','Z'); $max = count($characters) - 1; for ($i = 0; $i < $length; $i++) { $rand = mt_rand(0, $max); $str .= $characters[$rand]; } return $str; } /** Set Dynamically ACF Field Default Value */ add_filter('acf/load_field/name=cv_random_string', 'wpwebguider_acf_load_random_string_value', 99, 1); function wpwebguider_acf_load_random_string_value( $field ) { $random_code = wpwebguider_random_string(); if( $random_code ) { $field['default_value'] = $random_code; } return $field; } /** Add random string as slug, this doesn't work */ function acf_title_companies( $value, $post_id, $field ) { if ( get_post_type( $post_id ) == 'cv' ) { $new_title = get_field( 'cv_random_string', $post_id ) . ' ' . $value; wp_update_post( array( 'ID' => $post_id, 'post_name' => $new_title, ) ); } return $value; } add_filter( 'acf/update_value/name=cv_random_string', 'acf_title_companies', 10, 3 );
The topic ‘Adding a random string as slug för CPT’ is closed to new replies.