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.
The above is the detailed content of How to Restrict WooCommerce Product Purchases Based on Previous Purchases?. For more information, please follow other related articles on the PHP Chinese website!