Posted on

Add fee on checkout for auction winner

To add fee on checkout for auction winner you can use code snippet below in your functions.php file. To change percentage of fee just modify global_fee or fee_per_auction variable.

add_action( 'woocommerce_cart_calculate_fees', 'afw_add_fee_on_checkout' );	

function afw_add_fee_on_checkout( $cart_object ) {

    $global_fee = 0.00; 		// initialize special global fee, 0.25 = 25%
    $fee_per_auction = 0.30; 	// fee per product, 0.25 = 25%

    foreach ( $cart_object->cart_contents as $key => $value ) {

        $product_id_cart = $value['product_id']; //get the product id from cart
        $quantity = $value['quantity']; //get quantity from cart
        $product = wc_get_product( $product_id_cart  ); //

        if('auction' == $product->get_type()) :

        	if ($product->get_auction_closed() == 2){
            		$item_price = $value['data']->get_auction_current_bid(); //get product price	
            		$global_fee = $global_fee + $item_price * $quantity * $fee_per_auction;
            }		
       	endif;  

	}

    if( $global_fee > 0 ) {
    	WC()->cart->add_fee( 'Buyers Premium', $global_fee, true, 'standard' );
    }
}