try this:
function add_taxonomy_to_upload_dir( $upload ) {
if ( isset( $_REQUEST['post'] ) ) {
// wp-json/wp/v2/media
$post = get_post( $_REQUEST['post'] );
} elseif ( isset( $_REQUEST['post_id'] ) ) {
// wp-admin/async-upload.php
$post = get_post( $_REQUEST['post_id'] );
} else {
return $upload;
}
if ( ! $post || empty( $post->ID ) ) {
return $upload;
}
$taxonomy = 'category';
// Get the terms associated with the post
$terms = get_the_terms( $post->ID, $taxonomy );
if ( $terms && ! is_wp_error( $terms ) ) {
// Use the first term found
// Posts should only have one category assigned
$term = array_shift( $terms );
// Add the taxonomy name to the uploads path
$upload['path'] = path_join( $upload['path'], $term->slug );
$upload['url'] = path_join( $upload['url'], $term->slug );
}
return $upload;
}
add_filter( 'upload_dir', 'add_taxonomy_to_upload_dir' );