gpt4 book ai didi

wordpress - WooCommerce 产品变体买一送二 50%

转载 作者:行者123 更新时间:2023-12-04 15:31:18 25 4
gpt4 key购买 nike

我希望为特定的可变产品设置特定折扣,但对于某些选定的变体而不是所有变体:
例如:我的变量 ID - 1571
变体 ID - 1572
变体 ID - 1573
因此,如果客户购买一种产品,他们会以 50% 的折扣获得另一种(相同的)产品(购买一件产品可享受 50% 的折扣)。
我尝试了很多折扣插件,我发现最接近的是:

  • Pricing Deals for WooCommerce ,
  • Conditional Discounts for WooCommerce
  • WooCommerce Extended Coupon Features FREE

  • 使用其中的一些,我可以为每个产品设置小计折扣或折扣,但不完全是我想要的(买 1 送 1)。还有其他专业插件我不想去。
    我找到的最近的代码是 WooCommerce discount: buy one get one 50% off with a notice
    是否可以针对可变产品的特定产品变体(仅针对每个产品变体)对第二个项目进行折扣?
  • 马克
  • 最佳答案

    要为可变产品的某些特定产品变体在第二个项目上获得 50% 的折扣,您将使用以下内容:

    add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_2nd_at_50', 10, 1 );
    function add_custom_discount_2nd_at_50( $cart ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

    // YOUR SETTINGS:
    $product_variations_ids = array(1572, 1573); // <== HERE your targeted product variations

    // Initializing variables
    $discount = 0;
    $product_names = array();

    // Loop through cart items
    foreach ( $cart->get_cart() as $key => $cart_item ) {
    if ( in_array( $cart_item['variation_id'], $product_variations_ids ) ) {
    $qty = (int) $cart_item['quantity'];
    $price = (float) $cart_item['data']->get_price();
    $name = (string) $cart_item['data']->get_name();

    if ( $qty > 1 ) {
    $discount -= number_format( $price / 2, 2 );
    }
    elseif( $qty = 1 ) {
    $product_names[] = $name;
    }
    }
    }

    // Applying the discount
    if( $discount != 0 ){
    $cart->add_fee('Buy one get one 50% off', $discount );
    }

    // Display a custom reminder notice on cart page (otional)
    if( ! empty($product_names) ){
    wc_clear_notices(); // clear other notices on checkout page.
    if( ! is_checkout() ){
    wc_add_notice( sprintf(
    __( "Add one more to get 50%% off on the 2nd item for %s" ),
    '"<strong>' . implode(', ', $product_names) . '</strong>"'
    ), 'notice' );
    }
    }
    }
    代码位于您的事件子主题(或事件主题)的 functions.php 文件中,经过测试并有效。

    要以每件商品的 50% 折扣获得 1 件商品,而不是第 2 件商品的 50% 折扣,请替换:
    $discount -= number_format( $price / 2, 2 );
    经过:
    $multiplier = ( $qty % 2 ) === 0 ? $qty / 2 : ( $qty - 1 ) / 2;
    $discount -= number_format( $price / 2 * $multiplier, 2 );

    要在第二个项目上获得第二个免费而不是 50% 的折扣,请替换代码行:
    $discount -= number_format( $price / 2, 2 );
    经过:
    $discount -= $price;

    要为购买的每件商品免费获得 1 件商品,而不是第 2 件商品的 50% 折扣,请替换:
    $discount -= number_format( $price / 2, 2 );
    经过:
    $multiplier = ( $qty % 2 ) === 0 ? $qty / 2 : ( $qty - 1 ) / 2;
    $discount -= $price * $multiplier;

    关于wordpress - WooCommerce 产品变体买一送二 50%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61223671/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com