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, value 25.45 means fee of $25.45
    $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){

				// fee for auction with highest bid
				$item_price = $value['data']->get_auction_current_bid(); // get winning bid price	
				$global_fee = $global_fee + $item_price * $quantity * $fee_per_auction;

            } else {

				// fee for buy now auction
				$item_price = $value['data']->get_price(); // get buy now 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' );
    }
}

Fee for autocharge orders:


add_filter( 'auctions_for_woocommerce_stripe_automatic_charge', 'auctions_for_woocommerce_stripe_automatic_charge_addfee', 10, 2 );

function auctions_for_woocommerce_stripe_automatic_charge_addfee( $order, $auctions_id ) {

	$fee_per_auction = 0.10; // 10% fee

	$product      = wc_get_product( $auctions_id );
	$item_price   = $product->get_auction_current_bid();
	$global_fee   = $item_price * $fee_per_auction;
	$item_fee     = new WC_Order_Item_Fee();

	$item_fee->set_name( 'Buyers Premium' );
	$item_fee->set_amount( $global_fee );
	$item_fee->set_total( $global_fee );

	$order->add_item( $item_fee );

	return $order;
}