In WooCommerce, users must be restricted from purchasing certain products (e.g., "c", "d", "e") unless they have previously acquired specific "gatekeeper" products (e.g., "a", "b").
By implementing a conditional function, you can determine whether a user has purchased the required "gatekeeper" products in the past. Here's the code to achieve this:
function has_bought_items() { $bought = false; $prod_arr = array( '21', '67' ); $customer_orders = get_posts( array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => 'shop_order', 'post_status' => 'wc-completed' ) ); foreach ( $customer_orders as $customer_order ) { $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id; $order = wc_get_order( $customer_order ); foreach ($order->get_items() as $item) { if ( version_compare( WC_VERSION, '3.0', '<' ) ) $product_id = $item['product_id']; else $product_id = $item->get_product_id(); if ( in_array( $product_id, $prod_arr ) ) $bought = true; } } return $bought; }
Usage:
$restricted_products = array( '20', '32', '75' ); $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id; if ( !has_bought_items() && in_array( $product_id, $restricted_products ) ) { // Display inactive add-to-cart button } else { // Display normal add-to-cart button }
By applying this code, you effectively restrict access to specific products based on prior purchases, enhancing the user experience and ensuring that customers have access to only relevant items.
위 내용은 이전 구매를 기반으로 WooCommerce 제품 구매를 제한하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!