我在 WooCommerce 的結帳流程方面面臨挑戰。
我使用「B2B for WooCommerce」外掛程式來區分常規產品和 B2B 產品。場景如下:
1 - 未註冊的訪客將「常規」類別中的產品(預設可供未註冊的訪客使用)新增至其購物車。
2 - 在結帳頁面上,訪客決定註冊為 B2B 客戶(透過結帳頁面上的表單選擇欄位)。
3 - 註冊和結帳流程同時發生在這個頁面上。
如果用戶註冊為 B2B 客戶並且購物車中有「常規」產品,我希望阻止下訂單。 由於這兩個操作(註冊和結帳)同時發生,典型的 WooCommerce 掛鉤無法如預期般運作。
如何在結帳過程中驗證正在註冊的使用者角色和購物車內容,並在滿足條件時阻止訂單?或者也許有更好、更簡單的方法來做到這一點?
我嘗試了重置購物車並重新載入頁面的功能。
編輯:
使用者角色:Wwp_wholesaler
我創建了兩個 WooCommerce 產品類別:普通和批發。 所有訪客都可以看到「普通」。 在註冊該角色後,「Wwp_wholesaler」就可以看到「批發」。
選擇欄位的名稱屬性為:「afreg_select_user_role」。 選項的值屬性為“customer”(對於普通客戶)和“wwp_wholesaler”(對於批發商)。
P粉0142937382024-04-04 00:01:07
當偵測到 B2B 客戶的購物車中有常規商品時,以下程式碼將提前停止結帳流程。在這種情況下,常規商品將從購物車中刪除,並拋出錯誤訊息,從而避免下訂單。
注意:提供的使用者角色別名是錯誤的,因為使用者角色別名沒有大寫。
程式碼:
add_action( 'woocommerce_checkout_create_order', 'process_checkout_creating_order', 10, 2 ); function process_checkout_creating_order( $order, $data ) { global $current_user; $targeted_field = 'afreg_select_user_role'; // Checkout field key to target $targeted_role = 'wwp_wholesaler'; // User role slug (for B to B) $targeted_term = 'Normal'; // Category term for Regular items // Targeting B to B user role only if( ( isset($data[$targeted_field]) && $data[$targeted_field] === $targeted_role ) || in_array( $targeted_role, $current_user->roles ) ) { $cart = WC()->cart; // Cart live object $item_keys_found = array(); // Initializing // Loop through cart items to search for "regular" items foreach ( $cart->get_cart() as $item_key => $item ) { if ( has_term( $targeted_term, 'product_cat', $item['product_id']) ) { $item_keys_found[] = $item_key; } } // If regular items are found if ( count($item_keys_found) > 0 ) { // Loop through regular item keys (and remove each) foreach ( $item_keys_found as $item_key ) { $cart->remove_cart_item( $item_key ); } // Throw an error message, avoiding saving and processing the order throw new Exception( sprintf( __('You are not allowed to purchase "Regular" items.'. ' %d "Regular" %s been removed from cart. %s', 'woocommerce'), count($item_keys_found), _n('item has', 'items have', count($item_keys_found), 'woocommerce'), sprintf( '%s', get_permalink(wc_get_page_id('shop')), __('Continue shopping', 'woocommerce') ) ) ); } } }
程式碼位於子主題的functions.php 檔案中(或外掛程式中)。經過測試並可以工作。