登录时用用户名替换菜单项文本

问题描述 投票:0回答:1

我试图在用户成功登录后用名称替换Wordpress菜单项文本(Login)。

我有一个菜单项,其中{display_name}作为导航标签。

functions.php里面我到目前为止得到了以下内容。

function give_profile_name(){
    $user=wp_get_current_user();
    $name=$user->user_firstname; 
    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 ( '#name_a#'==$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;
}

用户登录后,菜单会正确显示用户名,但一旦退出,菜单仍然会在屏幕上显示{display_name}。如何将其更改为“登录”等文本?

wordpress custom-wordpress-pages
1个回答
0
投票

使用is_user_logged_in()来定义用户是否登录,或者不是这样:

// ...
if ( '#name_a#' == $menu_item->title ) {
    if ( is_user_logged_in() ) { // If logged in, get the name.
        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'] );
        }    
    } else { // If not, show "Login".
        $menu_item->title = __( 'Login', 'so_48051986' );
    }
}
// ...
© www.soinside.com 2019 - 2024. All rights reserved.