Please check the following code, you have to assign the custom taxonomy name to $taxonomy
variable. And only the first taxonomy term will be appended to the post slug.
add_filter( 'wp_insert_post_data', function( $data, $postarr ) {
/**
* Only for post posttype and when the post is created
*/
if ( empty( $postarr['save'] ) && isset( $data['post_type'] ) && 'post' === $data['post_type'] ) {
$taxonomy = 'custom-taxonomy-name'; // Add your custom taxonomy name
$tax_terms = array();
$slug = '';
/**
* Make sure custom taxonomy is really assigned
*/
if ( isset( $postarr['tax_input'] ) && isset( $postarr['tax_input'][ $taxonomy ] ) ) {
$tax_terms = array_filter( $postarr['tax_input'][ $taxonomy ] );
}
/**
* Only the first term slug will be appended
*/
if ( count( $tax_terms ) ) {
$term = get_term( current( $tax_terms ), $taxonomy );
if ( ! is_wp_error( $term ) && ! is_null( $term ) ) {
$slug = '-' . $term->slug;
}
}
/**
* Append the slug
*/
if ( $slug ) {
$data['post_name'] .= $slug;
}
}
return $data;
}, 10, 2 );