2 回答

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
根據(jù) Contact form 7 插件作者is_user_logged_in()
將在下面處理表單提交的情況:
subscribers_only: true
在表格的附加設(shè)置中設(shè)置。或者設(shè)置
WPCF7_VERIFY_NONCE
為真使用add_filter( 'wpcf7_verify_nonce', '__return_true' );
欲了解更多信息,請(qǐng)單擊此處。
此外,要更改用戶角色,您可以執(zhí)行以下操作:
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 );
}
}
}
}
}
}
如果您只想向用戶添加新角色并保留現(xiàn)有角色,則不要在set_role下面使用:
// Add a new role to the user while retaining the previous ones
$user->add_role( $role );

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
至于以編程方式設(shè)置用戶角色,您只需獲取用戶對(duì)象并使用 set_role() 函數(shù)將其角色更改為您想要的任何角色,只要該角色已定義。試試這種方式
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 關(guān)注
- 145 瀏覽
添加回答
舉報(bào)