[英]Displaying Logged-In User Name in Wordpress Menu
我正在將Wordpress與UserPro一起使用,並希望我的菜單顯示鏈接到用戶個人資料頁面的登錄用戶的名字。
問題是在我的菜單結構中,“配置文件”菜單選項應該具有一個包含“編輯配置文件”,“提交”和“注銷”的子菜單。
這是我當前的代碼:
/*earlier code, currently commented out, for function to
display username in menu using #profile_name# placeholder
function give_profile_name($atts){
echo userpro_profile_data('first_name', get_current_user_id());
}
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;
}
end of earlier code */
//currently in use, unlinked code
add_filter( 'wp_nav_menu_items', 'my_custom_menu_item');
function my_custom_menu_item($items)
{
if(is_user_logged_in())
{
$user=wp_get_current_user();
$name=$user->user_firstname;
$items .= '<li>'.$name.'';
}
return $items;
}
?>
我可以擺弄並嘗試通過擺弄Firebug的代碼來在菜單下添加子菜單,但這將意味着手動編輯functions.php中的所有鏈接,這將很繁瑣。
我希望能夠通過Wordpress菜單輕松添加,編輯,刪除和重定向子菜單項。
請指教。
好的,我找到了一個解決方案(它可以用於任何主題,任何插件,因為它僅使用WordPress核心功能)。
在菜單中,使用占位符命名希望用戶名出現的菜單項(例如:#profile_name#,#user#,#random#等)
現在,將以下代碼添加到您的子主題的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#替換為自定義占位符的名稱。
抱歉我誤用了“占位符”一詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.