| |
| <?php
|
| add_action('woocommerce_order_status_completed', 'create_user_and_notify_on_order_completion_with_masterstudy');
|
|
|
| function create_user_and_notify_on_order_completion_with_masterstudy($order_id) {
|
| $order = wc_get_order($order_id);
|
| $customer_email = $order->get_billing_email();
|
|
|
|
|
| $user = get_user_by('email', $customer_email);
|
|
|
| if ($user) {
|
|
|
| if (!in_array('customer', $user->roles)) {
|
| $user->add_role('customer');
|
| }
|
|
|
|
|
| $order->set_customer_id($user->ID);
|
| $order->set_billing_email($customer_email);
|
| $order->set_billing_first_name($user->first_name);
|
| $order->set_billing_last_name($user->last_name);
|
| $order->save();
|
|
|
|
|
| foreach ($order->get_items() as $item) {
|
| $product_id = $item->get_product_id();
|
| if (STM_LMS_Order::has_purchased_courses($user->ID, $product_id)) {
|
| STM_LMS_Course::add_user_course($product_id, $user->ID, 0, 0);
|
| STM_LMS_Course::add_student($product_id);
|
| }
|
| }
|
| } else {
|
|
|
| $first_name = $order->get_billing_first_name();
|
| $last_name = $order->get_billing_last_name();
|
|
|
|
|
| $password = $customer_email;
|
|
|
|
|
| $user_id = wp_create_user($customer_email, $password, $customer_email);
|
|
|
| if (!is_wp_error($user_id)) {
|
|
|
| wp_update_user([
|
| 'ID' => $user_id,
|
| 'first_name' => $first_name,
|
| 'last_name' => $last_name,
|
| 'role' => 'customer'
|
| ]);
|
|
|
|
|
| WC()->mailer()->emails['WC_Email_Customer_New_Account']->trigger($user_id, $password, true);
|
|
|
|
|
| update_post_meta($order_id, '_customer_user', $user_id);
|
|
|
|
|
| foreach ($order->get_items() as $item) {
|
| $product_id = $item->get_product_id();
|
| if (STM_LMS_Order::has_purchased_courses($user_id, $product_id)) {
|
| STM_LMS_Course::add_user_course($product_id, $user_id, 0, 0);
|
| STM_LMS_Course::add_student($product_id);
|
| }
|
| }
|
| } else {
|
| error_log('Failed to create user for order ' . $order_id . ': ' . $user_id->get_error_message());
|
| }
|
| }
|
| }
|
|
|
| |
| |
Comments