如何确定客户是否在 WooCommerce 中购买了特定产品?

Linda Hamilton
发布: 2024-11-14 13:22:02
原创
489 人浏览过

How Can I Determine if a Customer Has Purchased Specific Products in WooCommerce?

Check if a Customer Has Purchased Specific Products in WooCommerce

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板