問題:
商家面臨著防止特定商品未經授權購買的常見挑戰產品。在這種情況下,客戶必須擁有產品「a」或「b」的先前購買證明才能存取產品「c」、「d」和「e」。
解決方案:
在本綜合指南中,我們將為您提供自訂功能,用於確定客戶在啟用存取受限商品之前是否購買了必備產品。
function has_bought_items() { $bought = false; // Replace the numbers with your specific target product IDs $prod_arr = array( '21', '67' ); // Gather all customer orders $customer_orders = get_posts( array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => 'shop_order', // WooCommerce orders post type 'post_status' => 'wc-completed' // Only orders with "completed" status ) ); // Process each customer order foreach ( $customer_orders as $customer_order ) { // Handle WooCommerce version compatibility $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id; $order = wc_get_order( $customer_order ); // Iterate through products bought in the order foreach ($order->get_items() as $item) { // Product ID retrieval based on WooCommerce version if ( version_compare( WC_VERSION, '3.0', '<' ) ) $product_id = $item['product_id']; else $product_id = $item->get_product_id(); // Condition: Check if required product ID exists in the array of purchased products if ( in_array( $product_id, $prod_arr ) ) $bought = true; } } // Return true if the specific products have been purchased by the customer return $bought; }
使用:
在 WooCommerce在範本中實作操作產品加入購物車按鈕的功能,例如:
例如,在商店頁面的加入到購物車按鈕範本中(循環/ add-to-cart.php):
// Replace numbers with restricted product IDs $restricted_products = array( '20', '32', '75' ); // WooCommerce compatibility adjustment $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id; // Restricted product, inactive add-to-cart button if ( !has_bought_items() && in_array( $product_id, $restricted_products ) ) { // Display an inactive add-to-cart button with a custom message // Non-restricted product or allowed product after specific purchase } else { // Regular add-to-cart button code }
此範例動態停用特定產品的「加入購物車」按鈕,直到顧客證明之前購買了所需商品。
以上是如何透過要求客戶提供先前購買的證明來防止在 WooCommerce 中未經授權購買特定產品?的詳細內容。更多資訊請關注PHP中文網其他相關文章!