我正在尝试在我们的网站上实现一个功能,用户可以通过单击团队页面上的按钮加入团队(团队是在用户角色编辑器中设置的自定义角色)。但是,如果用户已经是该团队的成员,我不希望为他们显示该按钮。
我已经有了使某人能够加入团队的代码:
<?php
add_shortcode( \'select_marketing\', \'select_marketing\' );
function select_marketing() {
// Stop if user is not logged in.
if ( ! is_user_logged_in() )
return;
ob_start();
?>
<form method="post" action="">
<button class="btn btn-default" type="submit" name="role" value="marketing">Join this Team</button>
</form>
<?php
// Do not process anything if it\'s not $_POST
if ( ! isset( $_POST[\'role\'] ) )
return;
// Never trust user input.
$role = sanitize_key( $_POST[\'role\'] );
if ( ! in_array( $role, array( \'marketing\', ) ) )
return;
// Get the user object
$user = new WP_User( get_current_user_id() );
$index = key( $user->roles );
$user_role = $user->roles[ $index ];
// User already got that user
if ( $user_role == $role ) {
echo sprintf( __( \'You already have %s role.\' ), $role );
} else {
// update user role
$user->set_role( $role );
echo sprintf( __( \'Your role was changed to %s.\' ), $role );
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
?>
然而,就我的一生而言,我无法想出如何隐藏一个特定角色的按钮,在上面的示例中,它将是营销角色。
如果有人能帮我一把,我将不胜感激。
哦,如果有更优雅的方法来完成我正在努力实现的目标,请随时告诉我。我对wordpress和php很陌生。
以上代码在此帖子中稍作修改:How to allow registered users to change their user role through frontend?
SO网友:Cesar Henrique Damascena
尝试更改此代码
// Get the user object
$user = new WP_User( get_current_user_id() );
$index = key( $user->roles );
$user_role = $user->roles[ $index ];
// User already got that user
if ( $user_role == $role ) {
echo sprintf( __( \'You already have %s role.\' ), $role );
} else {
// update user role
$user->set_role( $role );
echo sprintf( __( \'Your role was changed to %s.\' ), $role );
}
至以下内容
//Get the user
$user = wp_get_current_user();
// User already got this role
if( $user->has_cap( $role ) ) {
echo sprintf( __( \'You already have %s role.\' ), $role );
// Do whatever you want
} else {
// update user role
$user->set_role( $role );
echo sprintf( __( \'Your role was changed to %s.\' ), $role );
}