問題陳述:
在WooCommerce 中,您需要限制以下能力購買特定產品(c、d、e),除非顧客之前購買過產品a 或b。如果滿足此條件,則應啟用產品c、d 和e 的購買按鈕;
解決方案:
實作條件函數來檢查客戶是否曾經購買過指定產品,並利用此函數來控制可見度和受限產品的購買按鈕功能。
代碼:
將以下條件函數添加到您的functions.php 文件中:
function has_bought_items() { $bought = false; // Specify the product IDs of restricted products $prod_arr = array( '21', '67' ); // Retrieve all customer orders $customer_orders = get_posts( array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => 'shop_order', // WC orders post type 'post_status' => 'wc-completed' // Only orders with status "completed" ) ); foreach($customer_orders as $customer_order) { // Compatibility for WooCommerce 3+ $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id; $order = wc_get_order( $customer_order ); // Iterate through purchased products in the order foreach($order->get_items() as $item) { // Compatibility for WC 3+ if(version_compare(WC_VERSION, '3.0', '<')){ $product_id = $item['product_id']; }else{ $product_id = $item->get_product_id(); } // Check if any of the designated products were purchased if(in_array($product_id, $prod_arr)){ $bought = true; } } } // Return true if a designated product was purchased return $bought; }
用法:
在相關的WooCommerce 模板(例如,loop/add-to-cart.php)中,您可以使用has_bought_items() 函數來控制購買按鈕的可見性和功能受限產品:
// Replace restricted product IDs as needed $restricted_products = array( '20', '32', '75' ); // Compatibility for WC +3 $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id; // Customer has not purchased a designated product for restricted products if( !has_bought_items() && in_array( $product_id, $restricted_products ) ) { // Display inactive add-to-cart button with custom text }else{ // Display normal add-to-cart button }
透過實施此條件檢查,您可以有效防止客戶在滿足指定的購買要求之前購買受限產品。
以上是如何根據先前在 WooCommerce 中的購買限制產品存取?的詳細內容。更多資訊請關注PHP中文網其他相關文章!