0

I'm trying to display the "Display_name" of an user in the menu. So I created a menu item called "#profile_name#".

It's working when i'm logged, but it displays "Untitled" when i'm not logged. Do you know why ?

   function give_profile_name(){
        $user=wp_get_current_user();
        $name=$user->display_name; 
        return $name;
    }

    add_shortcode('profile_name', 'give_profile_name');

    add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
    function my_dynamic_menu_items( $menu_items ) {
        foreach ( $menu_items as $menu_item ) {
            if ( '#profile_name#' == $menu_item->title ) {
                global $shortcode_tags;
                if ( isset( $shortcode_tags['profile_name'] ) ) {
                    // Or do_shortcode(), if you must.
                    $menu_item->title = call_user_func( $shortcode_tags['profile_name'] );
                }    
            }
        }

        return $menu_items;
    }

Thank you

  • Because if you are not logged wp_get_current_user() doesn't have a username, what do you want to show if the user is not logged in? And what do you want to show when the user is logged the username how is logged? – Castiblanco Sep 19 '18 at 14:26
  • I just want display the "Display_name" when user is logged in and display nothing when the user is not logged in. :) – Garrosh Sep 19 '18 at 14:30
  • Good, check my answer. – Castiblanco Sep 19 '18 at 14:31
  • Why are you using a shortcode here? Seems like overkill - all you need is if ( '#profile_name#' == $menu_item->title ) { $menu_item->title = give_profile_name(); } – Peter HvD Sep 19 '18 at 15:51
0

You should first check if the user is logged in, doing is_user_logged_in(), if so you get the username.

function give_profile_name(){
    if ( is_user_logged_in() ) {
        $user=wp_get_current_user();
        $name=$user->display_name; 
        return $name;
    } else {
        return "";
    }
}

You can also change your if to check if the shortcode is returning Untitled.

if ( isset( $shortcode_tags['profile_name'] ) && $shortcode_tags['profile_name'] != "Untitled")
  • Hello Castiblanco, thank you, but it displays me "Untitled" when I'm not logged in. – Garrosh Sep 19 '18 at 14:34
  • Try this new code, returning an empty string "" if the user is not logged in. – Castiblanco Sep 19 '18 at 14:35
  • Hum, still "Untitled", sorry – Garrosh Sep 19 '18 at 14:36
  • Hmm sounds like a cache problem or something, if you are returning something I cannot say the same. – Castiblanco Sep 19 '18 at 14:37
  • If I write for example "return "duh";" it's working. It seems doesn't accept empty string. – Garrosh Sep 19 '18 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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