skip to Main Content

I’ve been trying to combine the following two functions, but can only successfully perform either one or the other, not both at the same time. I was wondering if anyone knew what might be causing the conflict. These are executed upon the creation of a customer via a WooCommerce registration form, via the woocommerce_created_customer action.

Function: 1 (purpose is to update two fields which already exist on the user page thanks to ACF Pro)

function school_info_save( $customer_id ) {

    if( isset( $_POST['school_name'] ) ) {
        update_user_meta( $customer_id, 'school_name', sanitize_text_field($_POST['school_name']) );
    }

    if( isset( $_POST['school_email'] ) ) {
        update_user_meta( $customer_id, 'school_email', sanitize_email($_POST['school_email']) );
    }

}
add_action('woocommerce_created_customer', 'school_info_save', 20);

Function 2: (purpose is to then update the user role to student)

function update_to_student_role( $customer_id ) {

    if( isset( $_POST['school_name']) && isset( $_POST['school_email']) ) {
        wp_update_user( array( 'ID' => $customer_id, 'role' => 'student' ) );
    }

}
add_action('woocommerce_created_customer', 'update_to_student_role', 10);

I’ve tried these both at different priorities. Generally, if both are active, only the student role function will succeed. Just wondering if anyone can explain to me why wp_update_user prevents update_user_meta from working – if that’s actually what is occurring.

Additionally, I’ve also tried running the above functionality all within one function too, with the same result.

function school_info_save( $customer_id ) {

    $metas = array(
        'wp_capabilities' => array('student' => true),
        'school_name' => sanitize_text_field($_POST['school_name']),
        'school_email' => sanitize_email($_POST['school_email'])
    );

    if( isset( $_POST['school_name']) && isset( $_POST['school_email']) ) {
        foreach($metas as $key => $value) {
            update_user_meta( $customer_id, $key, $value );
        }
    }

}
add_action('woocommerce_created_customer', 'school_info_save', 20);

Thank you.

2

Answers


  1. Chosen as BEST ANSWER

    Nevermind... I had forgotten to actually modify the ACF field rules so that those two student fields appeared on a user profile which had a role of "student" ... the functions were working, but the fields weren't there to receive the data upon role change I believe.


  2. you can instead change your Function 2. Like this:

    function update_to_student_role( $new_customer_data ) {
    
        if( isset( $_POST['school_name']) && isset( $_POST['school_email']) ) {
            $new_customer_data['role'] = 'student';
        }
        return $new_customer_data;
    }
    add_action('woocommerce_new_customer_data', 'update_to_student_role');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search