So, I have following php code:

<?php global $my_profile; ?>
<?php if (is_user_logged_in()) : ?>
    <div class="img" data-key="profile"><?php echo get_avatar( get_current_user_id(), 64 ); ?></div>
<?php endif; ?>

It pulls the profile picture of currently logged in user. I am trying to add this to one of the menu item title, so that user profile picture is shown as a part of the menu.

It looks like I cannot directly add this code into menu.

What would be the best way to add this into one of the menu title?




2 Answers 2


Add to your functions file and use wp_nav_menu_items

add_filter('wp_nav_menu_items','wpsites_add_avatar_to_nav', 10, 2);
function wpsites_add_avatar_to_nav( $items, $args ) {
    if( $args->theme_location == 'primary' )
    return $items;    

    $dude = get_avatar( get_current_user_id(), 48 );

    if (is_user_logged_in()) : 
    echo'<li class="your-custom-class right">' . $dude . '</li>';

    return $items;

Might need to use output buffering.

Some work is required on your behalf to get your code working with this filter. You will need to change the class depending on which theme you're using.


You can try this out :

<?php global $my_profile; ?>
<?php if (is_user_logged_in()){
    $avatar = '<div class="img" data-key="profile">'.get_avatar( get_current_user_id(), 64 ).'</div>';
    $avatar = '';  
}  ?>

And your menu code should be like this

$defaults = array(
    'theme_location'  => 'location of menu in your theme',
    'menu'            => 'slug',
    'container'       => 'div',
    'menu_class'      => 'menu',
    'echo'            => true,
    'fallback_cb'     => 'wp_page_menu',
    'items_wrap'      => $avatar.'<ul id="%1$s" class="%2$s">%3$s</ul>',

wp_nav_menu( $defaults );

Fill all the parameters as per your requirement. For full list of parameter check this page https://codex.wordpress.org/Function_Reference/wp_nav_menu

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.