简体   繁体   中英

Is there a way to update a user role and update ACF fields on the user profile in WordPress at the same time using WooCommerce actions?

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.

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');

没关系......我忘记实际修改 ACF 字段规则,以便这两个学生字段出现在具有“学生”角色的用户配置文件中......功能正在运行,但字段不在那里接收我相信角色变化时的数据。

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