仅当在 Woocommerce 中应用优惠券时才允许购买特定产品

Zai*_*Ali 4 php wordpress cart coupon woocommerce

我正在 woocommerce 网站上工作,我试图限制仅在应用优惠券时才购买产品,因此在不添加优惠券代码的情况下不应对其进行处理。用户必须输入优惠券代码才能订购该特定产品(不适用于所有其他产品)。

任何帮助表示赞赏。

Loi*_*tec 5

对于指定产品,如果未应用优惠券,以下代码将不允许结账,并显示错误消息:

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
    $targeted_ids   = array(37); // The targeted product ids (in this array)
    $coupon_code    = 'summer2'; // The required coupon code

    $coupon_applied = in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() );

    // Loop through cart items
    foreach(WC()->cart->get_cart() as $cart_item ) {
        // Check cart item for defined product Ids and applied coupon
        if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) {
            wc_clear_notices(); // Clear all other notices

            // Avoid checkout displaying an error notice
            wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $cart_item['data']->get_name() ), 'error' );
            break; // stop the loop
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。

在此输入图像描述

并在结帐时:

在此输入图像描述