我正在尝试在用户成功登录后将Wordpress菜单项文本(登录(替换为名称。
我有一个菜单项,{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}
。我如何将其更改为"登录"之类的文本?
使用 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' );
}
}
// ...