How to display user's avatar on the top of main menu in WordPress admin panel?

I got a requirement to update the WordPress's admin panel, where I need to display the current user's avatar on the top of admin's main menu(see the screenshot).

Topic avatar Wordpress

Category Web


I'm not sure if core offers any hooks well suited to this purpose. I certainly don't see any purpose-fit hooks in the source which renders the admin menu.

But on a more hacky whim, this could be relatively easily accomplished using a add_menu_item() with $position 0, then modifying the new menu item registration in the $menu global in order to adjust any parameters as necessary.

function wpse391894_admin_menu_avatar() {
  global $menu;

  $user  = wp_get_current_user();
  $title = sprintf(
    __( 'Howdy, %s', 'wpse391894' ),
    esc_html( $user->display_name )
  );
  $img   = get_avatar( $user );

  add_menu_page(
    $title,
    sprintf(
      "%s\n%s",
      $img,
      $title
    ),
    'read',
    'wpse391894-dummy-slug',
    '',
    'none',
    0
  );

  // Look up a reference to the new menu item registration array.
  $item = &$menu[ array_key_last( $menu ) ];

  // Modify the link?
  $item[2] = "user-edit.php?user_id={$user->ID}";
}

add_action( 'admin_menu', 'wpse391894_admin_menu_avatar' );

enter image description here

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.