Problem:
You need to determine if a customer has made previous purchases of specific products (e.g., "a" or "b") in WooCommerce. This is necessary to restrict their ability to purchase other products (e.g., "c", "d", "e") unless they have met the specified prerequisite.
Solution:
Below is a customizable function, has_bought_items(), that evaluates whether the current customer has previously purchased any items from a provided array of product IDs.
Code:
function has_bought_items() { $bought = false; // Set the desired product IDs $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', 'post_status' => 'wc-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( $order_id ); // Iterate through customer purchases foreach ($order->get_items() as $item) { // Compatibility for WooCommerce 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 restricted products were purchased if ( in_array( $product_id, $prod_arr ) ) $bought = true; } } // Return true if a restricted product has been purchased return $bought; }
Usage:
To use this function, place it in your theme's functions.php file and make modifications to the $prod_arr array as needed. Then, you can integrate it into your WooCommerce templates to conditionally display or disable add-to-cart buttons based on the customer's purchase history.
For example, in the add-to-cart.php template, you could use the following code:
if ( !has_bought_items() && in_array( $product_id, $restricted_products ) ) { // Make add-to-cart button inactive (disabled styling) // Display explicit message if desired } else { // Display normal Add-To-Cart button }
以上是如何确定客户是否在 WooCommerce 中购买了特定产品?的详细内容。更多信息请关注PHP中文网其他相关文章!