嵌入编辑帐户表单的快捷代码不起作用

时间:2020-07-09 作者:023023

我正在创建一个短代码,如果用户已登录,则显示其名字和姓氏;如果用户已登录,但尚未配置任何名称,则会返回一个随机名称,并显示一条消息,告诉他编辑个人资料。我成功地获得了名称,但没有显示出如果用户没有名称应该出现的文本。代码:

// Show name if logged in - PT e ENG
function colaborador_nome($atts)
{
    if (is_user_logged_in() && !is_feed()) {
          return \'&nbsp;\' .    $username = \'<a href="\' . ( admin_url(\'profile.php\') .\'">\' . get_user_meta(get_current_user_id(), \'first_name\' , true) . \'&nbsp;\' .
        (($username = get_user_meta(get_current_user_id(), \'last_name\', true)  . \'</a>\')  ? $username : \'&nbsp;<a href="\' . admin_url(\'profile.php\') . \'">Noe Name [edit profile]</a>"\'));   
    }
}
add_shortcode(\'colaborador_nome\', \'colaborador_nome\');
不工作的部分:

 ? $username : \'&nbsp;<a href="\' . admin_url(\'profile.php\') . \'">Noe Name [edit profile]</a>"\'

1 个回复
最合适的回答,由SO网友:Ivan Shatsky 整理而成

You absolutely did not understand how the code from my previous answer works, yeah? The PHP ternary operator $result = $a ? $b : $c works the same way as the following construction:

if ( $a ) {
    $result = $b;
} else {
    $result = $c;
}

So the whole idea was to check if the get_user_meta(get_current_user_id(), \'last_name\', true) function returns an empty value. When you change it to

($username = get_user_meta(get_current_user_id(), \'last_name\', true)  . \'</a>\') ? ...

you break the whole logic, because that

get_user_meta(get_current_user_id(), \'last_name\', true)  . \'</a>\'

string would never have an empty value (that should be quite obvious, even if the get_user_meta() function returns an empty value, the whole string would be equal to \'</a>\'). Use this statement:

return \'&nbsp;<a href="\' . admin_url(\'profile.php\') . \'">\' . ( ( $username = get_user_meta( get_current_user_id(), \'last_name\', true ) ) ? $username : ">Noe Name [edit profile]" ) . \'</a>\';

Update

If you want to work with several user meta fields, I recommend to use get_userdata() function:

function colaborador_nome($atts)
{
    if (is_user_logged_in() && !is_feed()) {
        $userdata = get_userdata( get_current_user_id() );
        $username = trim( implode( \' \', array( $userdata->first_name, $userdata->last_name ) ) );
        return \'&nbsp;<a href="\' . admin_url(\'profile.php\') . \'">\' . ( $username ? $username : ">Noe Name [edit profile]" ) . \'</a>\';
    }
}

I still don\'t understand why the shorthand form of ternary operator doesn\'t work for you, using it would help to simplify the return statement to

return \'&nbsp;<a href="\' . admin_url(\'profile.php\') . \'">\' . ( $username ?: ">Noe Name [edit profile]" ) . \'</a>\';

相关推荐

Wp-admin/EDIT-TAGS.php?Taxonomy=CATEGORY上缺少一些类别

当我去/wp-admin/edit-tags.php?taxonomy=category它说共有19个类别,但只列出其中的13个。没有第二页可转到。如果我在类别中搜索"E;,所有19个都出现了。如果我单击;父类别“;在左侧,它显示下拉列表中的所有19个。除了主类别列表页面之外,几乎所有其他地方都有。什么会导致此问题?我如何解决它?