UserWoocommerce

How change user role after woocommerce product purchase (and revert after certain time)

How change user role after woocommerce product purchase (and revert after certain time)

With this ready made snippet, you can configure a product in woocommerce, that when bought, the role of the user, updates. At the same time, it sets a crone job that will change the user role automatically after a set period of time.

    
add_action( 'woocommerce_order_status_completed', 'ecommercehints_change_user_role_after_purchase' ); function ecommercehints_change_user_role_after_purchase( $order_id ) { $order = wc_get_order( $order_id ); $items = $order->get_items(); $eligible_product_ids = array( '128', '31', '69' ); // Only change if any one of these product IDs are in the order foreach ( $items as $item ) { if ( $order->user_id > 0 && in_array( $item['product_id'], $eligible_product_ids ) ) { $user = new WP_User( $order->user_id ); $user->remove_role( 'customer' ); // The default Customer role is removed $user->add_role( 'subscriber' ); // The new role is added // Check if there is a scheduled event and cancel it $scheduled_event = wp_get_scheduled_event( 'ecommercehints_change_user_role_back', array( $order->user_id ) ); if ( $scheduled_event ) { wp_clear_scheduled_hook( 'ecommercehints_change_user_role_back', array( $order->user_id ) ); } // Schedule an event to change the user role back after 1 day wp_schedule_single_event( time() + 86400, 'ecommercehints_change_user_role_back', array( $order->user_id ) ); break; } } } // Function to change the user role back to the original role add_action( 'ecommercehints_change_user_role_back', 'ecommercehints_change_user_role_back' ); function ecommercehints_change_user_role_back( $user_id ) { $user = new WP_User( $user_id ); $user->remove_role( 'subscriber' ); // The new role is removed $user->add_role( 'customer' ); // The original role is added back }

Leave a Reply