且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Wordpress 菜单中显示登录用户名

更新时间:2023-11-30 17:50:04

好的,我找到了一个解决方案(它可以用于任何主题,任何插件,因为它只使用核心 WordPress 功能).

Okay, I found a solution (and it can be used for any theme, with any plugin as it only uses core WordPress functions).

在菜单中,使用占位符命名要显示用户名的菜单项(例如:#profile_name#、#user#、#random# 等)

In the menu, name the menu item where you want the user's name to appear with a place-holder (such as: #profile_name#, #user#, #random#, etc.)

现在,将以下代码添加到您的子主题的functions.php:

Now, add the following code to the your child-theme's functions.php:

function give_profile_name($atts){
    $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 ( '#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;
} 

如果您使用自己的占位符,请记住在上面的代码中将#profile_name# 替换为您的自定义占位符的名称.

In case you're using your own place-holder, remember to replace #profile_name# with the name of your custom place-holder in the code above.

抱歉,我误用了占位符"一词.

Apologies in case I've misused the term 'place-holder'.