diff --git a/inc/namespace.php b/inc/namespace.php index 0d360d3..0156037 100644 --- a/inc/namespace.php +++ b/inc/namespace.php @@ -47,6 +47,7 @@ function bootstrap() : void { add_action( 'pre_get_posts', __NAMESPACE__ . '\\action_pre_get_posts', 9999 ); add_action( 'wp', __NAMESPACE__ . '\\action_wp' ); add_action( 'wp_insert_post', [ $insert_post_handler, 'action_wp_insert_post' ], 10, 3 ); + add_action( 'profile_update', __NAMESPACE__ . '\\update_author_term_name', 10, 3 ); // Filters. add_filter( 'wp_insert_post_data', [ $insert_post_handler, 'filter_wp_insert_post_data' ], 10, 3 ); @@ -59,6 +60,32 @@ function bootstrap() : void { add_filter( 'comment_notification_recipients', __NAMESPACE__ . '\\filter_comment_notification_recipients', 10, 2 ); } +/** + * Sync author term name with user display name. + * + * @param int $user_id User ID. + * @param WP_User $old_user_data Old user data. + * @param array $userdata User data. + * @return void + */ +function update_author_term_name( int $user_id, WP_User $old_user_data, array $userdata ) : void { + // User doesn't exist in authorship taxonomy. + $term = get_term_by( 'slug', (string) $user_id, TAXONOMY ); + if ( ! $term ) { + return; + } + + $display_name = isset( $userdata['display_name'] ) ? $userdata['display_name'] : ''; + // User display name hasn't changed. + if ( $term->name === $display_name ) { + return; + } + + wp_update_term($term->term_id, TAXONOMY, [ + 'name' => $userdata['display_name'], + ]); +} + /** * Return list of supported post types, defaulting to those supporting 'author'. *