WooCommerce基于产品ID的批量折扣。

问题描述 投票:1回答:1

我正在尝试在WooCommerce中编程一个批量折扣。

目前,我有以下内容

function se_bulkdiscount_on_ids( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    // Set special prices
    $special_price = array(
        2 => '1.2',
        3 => '1.3',
        4 => '1.4',
        5 => '1.5',
        6 => '1.6',
        7 => '1.7',
        8 => '1.8',
    );

    // Set product ids
    $specific_product_ids = array( 1465, 1785 );

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) { 
        // Get product id
        $product_id = $cart_item['product_id'];
        // Compare
        if ( in_array( $product_id, $specific_product_ids ) ) {
            foreach($special_price as $quantity => $price){
                if($cart_item['quantity'] >= $quantity){
                    $cart_item['data']->set_price( $price );
                }
            }          
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'se_bulkdiscount_on_ids', 10, 1 );

但我怎么能把这个折扣只设置在特定的产品ID上呢?

如果我有ID 1300 1x和1403 2x这有3个一起的数量比价格是1.62每件。

php wordpress woocommerce cart hook-woocommerce
1个回答
1
投票

假设你说的是这个吗,请在代码中添加注释和解释

function se_bulkdiscount_on_ids( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

    /* SETTINGS */

    // Set special prices
    $special_price = array(
        1 => 1.1,   
        2 => 1.2,
        3 => 1.3,
        4 => 1.4,
        5 => 1.5,
        6 => 1.6,
        7 => 1.7,
        8 => 1.8,
    );

    // Set product ids
    $specific_product_ids = array( 30, 813 );

    /* END SETTINGS */

    // total items
    $count = 0;

    // Loop through cart items (count)
    foreach ( $cart->get_cart() as $cart_item ) {    
        // Get product id
        $product_id = $cart_item['product_id'];

        // Quantity
        $product_quantity = $cart_item['quantity'];

        // Compare
        if ( in_array( $product_id, $specific_product_ids ) ) {
            $count += $product_quantity;
        }
    }

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {    
        // Get product id
        $product_id = $cart_item['product_id'];

        // Compare
        if ( in_array( $product_id, $specific_product_ids ) ) {
            // If count is in range of the array
            if ( $count >= 2 & $count <= count( $special_price ) ) {
                // set new price
                $cart_item['data']->set_price( $special_price[$count] );                    
            } elseif ( $count > count( $special_price ) ) {
                // set new price
                $cart_item['data']->set_price( end($special_price) );       
            }             
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'se_bulkdiscount_on_ids', 10, 1 );
© www.soinside.com 2019 - 2024. All rights reserved.