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' );
    }
}