Add a fee to WooCommerce per product, based on category

后端 未结 2 1904
别那么骄傲
别那么骄傲 2020-12-05 06:15

I\'ve been trying for a while now to get this working but I haven\'t find any solution that does exactly what we need, and I\'m far from an expert in PHP so I\'m a bit lost.

2条回答
  •  甜味超标
    2020-12-05 06:23

    thanks for posting this above code. I had needed exactly this, but there were some problems for, me. I didn't want the category to be a part of it, i wanted it to apply to all products, and I also required a fixed fee per product.

    The other problem I had was if I had 2 different products in the cart it would only calculate it as 1 product. so I did some research and found a way for it to calculate the total number of products in the cart. So here is the final code I came out with. Thought it may help someone else looking for a similar answer

    /** add handling fee **/
    function df_add_handling_fee( $cart_object ) {
    
    global $woocommerce;
    // $specialfeecat = 3711; // category id for the special fee
    $spfee = 0.00; // initialize special fee
    $spfeeperprod = 10; //special fee per product
    
    //Getting Cart Contents. 
    $cart = $woocommerce->cart->get_cart();
    //Calculating Quantity
    foreach($cart as $cart_val => $cid){
       $qty += $cid['quantity']; 
    }
    foreach ( $cart_object->cart_contents as $key => $value ) {
    
        $proid = $value['product_id']; //get the product id from cart
        //$quantiy = $value['quantity']; //get quantity from cart
        $itmprice = $value['data']->price; //get product price
    
        $terms = get_the_terms( $proid, 'product_cat' ); //get taxonamy of the prducts
        if ( $terms && ! is_wp_error( $terms ) ) :
            foreach ( $terms as $term ) {
                //$catid = $term->term_id;
                //if($specialfeecat == $catid ) {
                    $spfee = $qty * $spfeeperprod;
                //}
            }
        endif;  
    }
    
    if($spfee > 0 ) {
    
        $woocommerce->cart->add_fee( 'Handling Fee', $spfee, true, 'standard' );
    }
    
    }
    
    add_action( 'woocommerce_cart_calculate_fees', 'df_add_handling_fee' );
    

    As you can see I have just commented out the parts from the original code. Hope someone can benefit from this :)

提交回复
热议问题