The second argument of wp_unique_post_slug
filter is post id. You can utilize that to generate the slug only once while creating the post for the first time.
Method 1:
add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );
function unique_slug_108286( $slug, $postId ) {
if ( ! $postId ) {
$n = 4;
$slug = bin2hex( random_bytes( $n ) ); //just an example
}
return $slug;
}
Other method would be using post meta to indicate whether a slug has been generated.
Method 2:
add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );
function unique_slug_108286( $slug, $postId ) {
if ( $postId && ! get_post_meta( $postId, 'slug_generated', true ) ) {
$n = 4;
$slug = bin2hex( random_bytes( $n ) ); //just an example
update_post_meta( $postId, 'slug_generated', true );
}
return $slug;
}