I would like to add an action in woocommerce to remove the tax from orders when created in the backend and for special users as customers.
This code is working for the normal order process on the website, but not on the backend
add_action( 'woocommerce_checkout_update_order_review', 'remove_tax_from_user' );
add_action( 'woocommerce_before_cart_contents', 'remove_tax_from_user' );
function remove_tax_from_user( $post_data ) {
global $woocommerce;
$username = $woocommerce->customer->get_username();
$user = get_user_by('login',$username);
if($user)
{
if( get_field('steuer_befreit', "user_{$user->ID}") ):
$woocommerce->customer->set_is_vat_exempt( true );
endif;
}
}
In backend customer needs to be "exempt of Vat" before clicking on "Add order" .
You could try to use the hook save_post_shop_order
that is triggered before order data is saved in backend, this way:
add_action( 'save_post_shop_order', 'backend_remove_tax_from_user', 50, 3 );
function backend_remove_tax_from_user( $post_id, $post, $update ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id; // Exit if it's an autosave
if ( $post->post_status != 'publish' )
return $post_id; // Exit if not 'publish' post status
if ( ! current_user_can( 'edit_order', $post_id ) )
return $post_id; // Exit if user is not allowed
if( ! isset($_POST['customer_user']) ) return $post_id; // Exit
if( $_POST['customer_user'] > 0 ){
$customer_id = intval($_POST['customer_user']);
if( get_field('steuer_befreit', "user_{$customer_id}") ){
$wc_customer = new WC_Customer( $customer_id );
$wc_customer->set_is_vat_exempt( true );
}
}
}
Code goes in function.php file of your active child theme (or theme).
But this will not work and you will not be able with any exiting hook to make that work. The only way Is to make first customer exempt of vat, then you can Add an order for this customer.