You can use the wp_insert_post_data
filter, and check the post_category
array for your category ID. (If $update
is false
, you’ll know it’s a new post being added, not an existing post being edited.)
Something like this should work.
add_filter( 'wp_insert_post_data', 'wpse414180_maybe_change_slug', 10, 4 );
/**
* Changes the slug on posts in the Poetry category.
*
* @param array $data The sanitized, slashed, processed post data.
* @param array $postarr The sanitized, slashed post data.
* @param array $unclean The slashed post data. Unsanitized. We won't use this.
* @param bool $update Is this a post update?
* @return array The (possibly filtered) post data.
*/
function wpse414180_maybe_change_slug( $data, $postarr, $unclean, $update ) {
if ( $update ) {
// This is an existing post being updated; return.
return $data;
}
$poetry_category = get_category_by_slug( 'poetry' );
if ( empty( $poetry_category ) ) {
// No poetry category, so we return early.
return $data;
}
if ( in_array( $poetry_category->term_id, $postarr['post_category'] ) ) {
// Random 7-digit number. Note: no collision checking.
$data['post_name'] = rand( 1000000, 9999999);
}
return $data;
}
Note
This code is untested and meant as a starting point, not necessarily a finished product; try it out on a test site first.
I haven’t added anything to make sure a given slug (ie, post_name
) isn’t already in use.