如何根据之前的购买限制 WooCommerce 产品购买?

Linda Hamilton
发布: 2024-11-15 05:28:02
原创
289 人浏览过

How to Restrict WooCommerce Product Purchases Based on Previous Purchases?

Verifying User Product Purchases in WooCommerce

Problem

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").

Solution

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;
}
登录后复制

Implementation

Usage:

  • Shop Page: Override loop/add-to-cart.php in your child theme and apply the following logic:
$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
}
登录后复制
  • Product Pages: Override relevant templates in single-product/add-to-cart folder and use the same logic as above.

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.

以上是如何根据之前的购买限制 WooCommerce 产品购买?的详细内容。更多信息请关注PHP中文网其他相关文章!

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