简体   繁体   中英

Contact Form 7 change user role after submitting

Okay I've been trying to make the following:

If current user role is SUBSCRIBER and contact form id "1234" has been successfully submitted, then change user role to EDITOR.

This is what I made so far, but I can't figure out why it doesn't work.

add_action( 'wpcf7_mail_sent', 'changerole_wpcf7' );

function changerole_wpcf7( $contact_form ) {
$user = wp_get_current_user();
     if ( ! empty( $user ) && in_array( "subscriber", (array) $user->roles ) && $contact_form->id() !== 1234 )
       return;
         $user->remove_role( "subscriber" );
         $user->add_role( "editor" );

    
}

Alright folks I finally made it work. I made some small changes to @rank code and also added subscribers_only: true to the "Additional Settings" tab in Contact Form 7.

add_action( 'wpcf7_mail_sent', 'changerole_wpcf7' );

function changerole_wpcf7( $cf7 ) {

    if ( is_user_logged_in() ) {
        $user = wp_get_current_user();
        $user_id = $user->ID;
        $user_meta = get_userdata($user_id);
        $user_roles = $user_meta->roles;      
        $submission = WPCF7_Submission::get_instance();
        
        if ( $cf7->id() == 1234 ) {
          if($submission) {
            if ( in_array( 'subscriber', $user_roles ) ) {
                wp_update_user( array( 'ID' => $user_id, 'role' => 'editor' ) );
                
            }
        }
    } else { return; }

}
}

Using return terminates the execution of your function. So you will never get to the part where you remove and and add the role.


Edit : Try it with other hook "wpcf7_before_send_mail" and check if user is logged in. You can update the user role instead of remove and adding it.

add_action( 'wpcf7_before_send_mail', 'changerole_wpcf7' );

function changerole_wpcf7( $contact_form ) {

    if ( is_user_logged_in() ) {
        $user = wp_get_current_user();
        $user_id = $user->ID;
        $user_meta = get_userdata($user_id);
        $user_roles = $user_meta->roles;

        if ( $contact_form->id() == 1234 ) {
            if ( in_array( 'subscriber', $user_roles ) ) {
                wp_update_user( array( 'ID' => $user_id, 'role' => 'editor' ) );
            }
        }
    } else { return; }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM