我正在将Wordpress与UserPro一起使用,并希望我的菜单显示登录用户的名字,链接到用户配置文件页面。
问题是,在我的菜单结构中,“Profile”菜单选项应该有一个子菜单,其中包含“edit Profile”、“submit”和“logout”。
这是我当前使用的代码:
/*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的代码,在菜单下添加子菜单,但这意味着手动编辑函数中的所有链接。php,这将是乏味的。
我希望能够通过Wordpress菜单轻松添加、编辑、删除和重定向子菜单项。
请告知。
最合适的回答,由SO网友:Akash kapur 整理而成
好的,我找到了一个解决方案(它可以用于任何主题,任何插件,因为它只使用核心WordPress函数)。
在菜单中,命名要在其中显示用户名并带有占位符的菜单项(请参见下面的屏幕截图)。示例:#profile\\u name#、#user#、#random#

现在,将以下代码添加到您的子主题的函数中。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\\u name#替换为自定义占位符的名称。
抱歉,如果我误用了“占位符”一词。