/** * Aelia EU VAT Assistant for WooCommerce - Make VAT number required when one * or more product from specific categories are in the cart. * * HOW TO USE THIS CODE * Add the code to the bottom of your theme's functions.php file (see https://www.skyverge.com/blog/add-custom-code-to-wordpress/). * The code will intercept the checkout process automatically and set the VAT number * field as "required", depending on the content of the cart. * * GPL DISCLAIMER * Because this code program is free of charge, there is no warranty for it, to the extent permitted by applicable law. * Except when otherwise stated in writing the copyright holders and/or other parties provide the program "as is" * without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of * merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of the program * is with you. should the program prove defective, you assume the cost of all necessary servicing, repair or correction. * * Need a consultation, or assistance to customise this code? Find us on Codeable: https://aelia.co/hire_us */ /** * Returns the categories assigned to a product. * * @param WC_Product product * @return array */ function aelia_get_product_categories($product) { $result = array(); // Get all the categories to which a product is assigned $categories = wp_get_post_terms($product->get_id(), 'product_cat'); // The $categories array contains a list of objects. Most likely, we would // like to have categorys slug as a keys, and their names as values. The // wp_list_pluck() function is perfect for this $categories = wp_list_pluck($categories, 'name', 'slug'); return $categories; } /** * Makes the VAT number required when products from specific categories are * added to the cart. * * @param bool vat_number_required * @param string customer_country * @return bool */ add_filter('wc_aelia_euva_order_is_eu_vat_number_required', function($vat_number_required, $customer_country) { // If the VAT number is already required, just return the flag as it is if($vat_number_required) { return $vat_number_required; } // An array of category IDs for which the VAT number is required $categories_requiring_vat_number = array( 'category1', 'category2', ); foreach(WC()->cart->get_cart() as $item) { // $item['data'] contains a product instance if(!empty($item['data'])) { // The keys of the returned array are the category IDs $product_categories = array_keys(aelia_get_product_categories($item['data'])); $matching_categories = array_intersect($categories_requiring_vat_number, $product_categories); // As soon as we find one product from one of the "VAT number required" // categories, we can stop if(!empty($matching_categories)) { $vat_number_required = true; } } } return $vat_number_required; }, 10, 2);