当定义的产品是 WooCommerce 购物车时添加折扣

我试图为两种产品都在购物车中时设置折扣,无论其中还有其他什么产品。


到目前为止,所需要的只是数组中的两个之一。


add_action( 'woocommerce_cart_calculate_fees', 'discount_for_ab_products' );

function discount_for_ab_products( $cart ) {


$product_ids = array(34,35);


    foreach ($product_ids as $product_id => $product) {


    $product_cart_id = WC()->cart->generate_cart_id( $product );

    $product_ab_in_cart = WC()->cart->find_product_in_cart( $product_cart_id );


    if ( $product_ab_in_cart ) {

        

        $discount = $cart->subtotal * 0.1;


        $cart->add_fee( __( 'Discount', 'woocommerce' ) , -$discount );

        }

    }

}


慕桂英4014372
浏览 142回答 1
1回答

米脂

请尝试以下操作,当所有定义的产品 ID 都在购物车中时(在您的情况下是两个),这将提供折扣:add_action( 'woocommerce_cart_calculate_fees', 'x_products_discount' );function x_products_discount( $cart ) {&nbsp; &nbsp; // Settings below&nbsp; &nbsp; $product_ids = array(34, 35); // <== Your defined product Ids&nbsp; &nbsp; $percentage&nbsp; = 10; // <== discount in percentage (10% here)&nbsp; &nbsp; $found_ids&nbsp; &nbsp;= array();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Loop through cart items&nbsp; &nbsp; foreach (WC()->cart->get_cart() as $cart_item ) {&nbsp; &nbsp; &nbsp; &nbsp; // Loop through defined product Ids&nbsp; &nbsp; &nbsp; &nbsp; foreach( $product_ids as $product_id ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if( in_array( $product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $found_ids[$product_id] = $product_id;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Discount part&nbsp; &nbsp; if( count( $found_ids ) === count( $product_ids ) ) {&nbsp; &nbsp; &nbsp; &nbsp; $cart->add_fee( __( 'Discount', 'woocommerce' ), -( $cart->subtotal * $percentage / 100 ) );&nbsp; &nbsp; }}代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。
打开App,查看更多内容
随时随地看视频慕课网APP