Woocommerce 中登录用户的单个特定产品购买

Single specific Product purchase for logged in users in Woocommerce

我的 Woocommerce 商店的注册用户是否可能只能购买一次特定产品?

此外,如果他们尝试重新购买该特定产品,则会提示一条警告消息,他们将无法签出……

可以用这两个钩子函数来完成(仅对登录用户有效)

1) 第一个将检查:

  • 特定产品尚未在购物车中(避免添加到购物车)
  • 客户之前没有购买过该产品(避免添加到购物车)

2) 第二个,将删除该特定产品的数量字段,只允许将一种产品添加到购物车。

代码(您必须在两个函数中设置您的特定产品 ID):

// Check on add to cart action and display a custom notice
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 3 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity ) {
    if ( ! is_user_logged_in() ) return $passed; // Only logged in users

    // HERE define your targeted Product ID
    $targeted_product_id = 37;

    // Check if customer has already bought the targeted Product ID
    if( wc_customer_bought_product( '', get_current_user_id(), $targeted_product_id ) ){
        //$passed = false;
        //$notice = __('You have already bought this product once', 'woocommerce');
    }

    // Check if product is in cart items
    if ( ! WC()->cart->is_empty() )
        foreach( WC()->cart->get_cart() as $cart_item )
            if( $cart_item['product_id'] == $targeted_product_id && $product_id == $targeted_product_id ){
                $passed = false;
                $notice = __('This product is already in cart', 'woocommerce');
                break;
            }

    // Displaying a custom error notice
    if( ! $passed )
        wc_add_notice( $notice, 'error' );

    return $passed;
}

// Removing the quantity field (allowing only one product quantity)
add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 10, 2 );
function custom_quantity_input_args( $args, $product ) {
    if ( ! is_user_logged_in() ) return $args; // Only logged in users

    // HERE define your targeted Product ID
    $targeted_product_id = 37;

    if( $product->get_id() != $targeted_product_id ) return $args;

    $args['input_value'] = 1; // Start from this value (default = 1)
    $args['min_value']   = 1; // Min value (default = 0)
    $args['max_value']   = 1; // Min value (default = 0)

    return $args;
}

代码进入活动子主题(或活动主题)的 function.php 文件。

已测试并有效。