Home >Backend Development >PHP Tutorial >How can I restrict product access based on previous purchases in WooCommerce?
Problem Statement:
In WooCommerce, you need to restrict the ability to purchase specific products (c, d, e) unless the customer has previously purchased either product a or b. If this condition is met, the purchase buttons for products c, d, and e should be enabled; otherwise, they should remain disabled.
Solution:
Implement a conditional function to check if a customer has previously purchased designated products and leverage this function to control the visibility and functionality of purchase buttons for restricted products.
Code:
Add the following conditional function to your functions.php file:
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; }
Usage:
In your relevant WooCommerce templates (e.g., loop/add-to-cart.php), you can use the has_bought_items() function to control the visibility and functionality of purchase buttons for restricted products:
// 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 }
By implementing this conditional check, you can effectively prevent customers from purchasing restricted products until they have met the specified purchase requirement.
The above is the detailed content of How can I restrict product access based on previous purchases in WooCommerce?. For more information, please follow other related articles on the PHP Chinese website!