Untitled

 avatar
unknown
plain_text
a year ago
2.2 kB
2
Indexable

add_action('woocommerce_before_calculate_totals', function($cart){
	
	if ( is_admin() && ! defined( 'DOING_AJAX' ) )
	    return;

	// Ensure the customer's billing country is fetched correctly
	$customer_billing_country = WC()->customer->get_billing_country();

	// Initialize an array to keep track of each seller's total sales in the cart
	$sellers_sales = array();

	// Loop through each cart item
	foreach ( $cart->get_cart() as $cart_item ) {
	    // Get the product ID and the seller ID (post author)
	    $product_id = $cart_item['product_id'];
	    $seller_id = get_post_field( 'post_author', $product_id );

	    // Initialize the seller's sales in the array if not already set
	    if ( ! isset( $sellers_sales[$seller_id] ) ) {
	        $sellers_sales[$seller_id] = 0;
	    }

	    // Add the line total to the seller's total sales
	    $sellers_sales[$seller_id] += $cart_item['line_total'];
	}

	// Loop through each seller's total sales to adjust tax if criteria are met
	foreach ( $sellers_sales as $seller_id => $total_sales ) {
	    // Fetch seller's billing country
	    $seller_billing_country = get_user_meta( $seller_id, 'billing_country', true );

	    // Check if the seller is from the UK, the buyer is from an EU country, and sales are over £135
	    if ( 'GB' === $seller_billing_country && is_eu_country( $customer_billing_country ) && $total_sales > 135 ) {
	        // Loop through cart items to set tax to zero for this seller's products
	        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

	            // Check if the current cart item belongs to the current seller
	            if ( $seller_id == get_post_field( 'post_author', $cart_item['product_id'] ) ) {
	                // Set the product prices to exclude tax
	                $cart->cart_contents[ $cart_item_key ]['data']->set_tax_status( 'none' );

	            }
	        }
	    }
	}
});

function is_eu_country( $country_code ) {
    $eu_countries = array( 'BE', 'BG', 'CZ', 'DK', 'DE', 'EE', 'IE', 'EL', 'ES', 'FR', 'HR', 'IT', 'CY', 'LV', 'LT', 'LU', 'HU', 'MT', 'NL', 'AT', 'PL', 'PT', 'RO', 'SI', 'SK', 'FI', 'SE' ); // Add or remove based on current EU members
    return in_array( $country_code, $eu_countries );
}
Leave a Comment