woocommerce运输取决于购物车

时间:2016-12-09 06:33:47

标签: php woocommerce woothemes

我的所有商品都有运费日的变化。周二或周五:

example

如果用户在星期二和星期五的购物车中有物品,我想收取额外费用。不知道如何将所有物品放入购物车,然后检查变化并修改运费。

function filter_woocommerce_add_to_cart(  ) {
global $woocommerce;
    $items = $woocommerce->cart->get_cart();
        if ( sizeof( $items ) >= 1 ) {
            foreach($items as $item => $values) { 
                $_product = $values['data'];
                echo "<script type='text/javascript'>alert('$_product ');</script>";
            }           
        } 
};

// add the filter 
add_filter( 'woocommerce_add_to_cart', 'filter_woocommerce_add_to_cart', 10, 2 );

我已经走到了这一步。在if内,我想打印产品数组,看看产品变异的价值是如何被调用的。但由于某种原因不起作用。

1 个答案:

答案 0 :(得分:0)

让它以这种方式工作

function get_variation_data_from_variation_id( $item_id ) {
    $_product = new WC_Product_Variation( $item_id );
    $variation_data = $_product->get_variation_attributes();
    $variation_detail = woocommerce_get_formatted_variation( $variation_data, true );  // this will give all variation detail in one line
    // $variation_detail = woocommerce_get_formatted_variation( $variation_data, false);  // this will give all variation detail one by one
    return $variation_detail; // $variation_detail will return string containing variation detail which can be used to print on website
    // return $variation_data; // $variation_data will return only the data which can be used to store variation data
}


// define the woocommerce_loop_add_to_cart_link callback 
function wc_ninja_change_flat_rates_cost( $rates, $package ) {
    if (WC()->cart->cart_contents_count > 1) {
        $cart_items = WC()->cart->get_cart();
        $first_item = array_shift($cart_items);
        $variation1 = get_variation_data_from_variation_id($first_item['data']->variation_id);
        foreach(  $cart_items as $cart_item ) { 
            $variations =   get_variation_data_from_variation_id($cart_item['data']->variation_id); 
             if( $variations  != $variation1 ){
                $rates['flat_rate:5']->cost = 20;
                break;
             }//end if
        } //end for
    } //end if
debug_to_console($rates);
    return $rates;
};

// add the filter 
add_filter( 'woocommerce_package_rates', 'wc_ninja_change_flat_rates_cost', 10, 2 );