2 回答
TA贡献1788条经验 获得超4个赞
根据 Contact form 7 插件作者is_user_logged_in()将在下面处理表单提交的情况:
subscribers_only: true在表格的附加设置中设置。或者设置
WPCF7_VERIFY_NONCE为真使用add_filter( 'wpcf7_verify_nonce', '__return_true' );
欲了解更多信息,请单击此处。
此外,要更改用户角色,您可以执行以下操作:
add_action( 'wpcf7_posted_data', 'tm_cf7_roles_posted_data' );
function tm_cf7_roles_posted_data( $posted_data ) {
$submission = WPCF7_Submission::get_instance();
$wpcf7 = WPCF7_ContactForm::get_current();
$formID = $wpcf7->id();
if ( $submission ) {
if( $formID == "YOUR-FORM-ID" ) {
if ( is_user_logged_in() ) {
$role = sanitize_key( $posted_data['radio-766'][0] );
if ( ! in_array( $role, array( 'subscriber', 'customer' ) ) )
return;
// Getting the WP_User object
$user = wp_get_current_user();
// The user exists
if( $user && $user->exists() ) {
// Check if user already has that role or not
if ( !in_array( $role, (array) $user->roles ) ) {
// Remove all the previous roles from the user and add this one
// This will also reset all the caps and set them for the new role
$user->set_role( $role );
}
}
}
}
}
}
如果您只想向用户添加新角色并保留现有角色,则不要在set_role下面使用:
// Add a new role to the user while retaining the previous ones
$user->add_role( $role );
TA贡献1805条经验 获得超10个赞
至于以编程方式设置用户角色,您只需获取用户对象并使用 set_role() 函数将其角色更改为您想要的任何角色,只要该角色已定义。试试这种方式
function tm_cf7_roles_posted_data( $posted_data ) {
// Stop if user is not logged in.
if ( ! is_user_logged_in() )
return;
ob_start();
$role = sanitize_key( $_POST['radio-766'] );
if ( ! in_array( $role, array( 'subscriber', 'customer' ) ) )
return;
$user = new WP_User( get_current_user_id() );
$index = key( $user->roles );
$user_role = $user->set_role($role);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_action( 'wpcf7_posted_data', 'tm_cf7_roles_posted_data' );
- 2 回答
- 0 关注
- 183 浏览
添加回答
举报
