如何確定客戶是否在 WooCommerce 中購買了特定產品?

Linda Hamilton
發布: 2024-11-14 13:22:02
原創
485 人瀏覽過

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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板