samedi 9 avril 2016

Add a percent fee to WooCommerce per product, based on category

Im new here although i've been using the website for months to gather some help from others questions.

Im trying to add a fee in woocommerce in the next way:

The site has to check the cart, find the products that meet a category id, calculate a percent fee of each of those products and sum them anc charge it.

So far i have managed to check the cart, find the products that meet a category (getting the amount of them) and multiply the ammount for a fixed fee.

As you can see if i have 3 products that meet the criteria (category id) at £50,£40 and £30, the fee will be 3*10 (the fixed fee is 10).

Whilst really what i want is that the site calculate the a percent fee from those products (50*10, 40*10, 30*10) and sum them up (500+400+300). Obviously not all products will have the same price.

Here is my code:

function df_add_handling_fee( $cart_object ) {

global $woocommerce;
$specialfeecat = 61; // 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 = $spfee + $quantiy * $spfeeperprod;
        }
    }
endif;  
}

if($spfee > 0 ) {

$woocommerce->cart->add_fee( 'Handling Fee', $spfee, true, 'standard' );
}

}

add_action( 'woocommerce_cart_calculate_fees', 'df_add_handling_fee' );

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire