Wordpress: Add extra fee in cart

2019-07-22 20:46发布

I've created a webshop in Woocommerce (wordpress). It's a wine shop and I need to add an extra cost: 0,08 euro per bottle (product).

I've found this and adjusted it, but I cannot get the number of products (bottles) to multiply with 0.08 euro. In the cart I do get an extra line but the value is 0.

Can anyone explain me what I'm doing wrong?

function get_cart_contents_count() {
     return apply_filters( 'woocommerce_cart_contents_count', $this->cart_contents_count );
}


function woo_add_cart_fee() {

  global $woocommerce;

  $woocommerce->cart->add_fee( __('Custom', 'woocommerce'), $get_cart_contents_count * 0.08 );

}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );

2条回答
迷人小祖宗
2楼-- · 2019-07-22 21:25

Try this code in your functions.php but it will be applied on over all cart

// Hook before adding fees 
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');

function add_custom_fees( WC_Cart $cart ){
    $fees = 0.08;
    $cart->add_fee( 'Handling fee', $fees);
}

EDIT: To multiply it with each product do something like

add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
function add_custom_fees( WC_Cart $cart ){
    $fees = 0;

    foreach( $cart->get_cart() as $item ){
       $fees += $item[ 'quantity' ] * 0.08; 
    }

    if( $fees != 0 ){
        $cart->add_fee( 'Handling fee', $fees);
    }
}
查看更多
乱世女痞
3楼-- · 2019-07-22 21:26

You are talking about adding surcharge to the cart. You can get all the related information from the Woocommerce Doc in here.

查看更多
登录 后发表回答