Do you want to show a particular list of billing countries based on the product ID in your customer’s cart, this code snippet is the solution!
function ts_countries_allowed_countries( $countries ) { // Cart or checkout page if ( is_cart() || is_checkout() ) { // The targeted product ids $targeted_ids = array( 96 ); // Country codes you want to show $show_countries = array( 'IN', 'NL', 'FR', 'ES' ); $found = false; if ( WC()->cart ) { // Loop through cart items foreach ( WC()->cart->get_cart() as $cart_item ) { if ( array_intersect( $targeted_ids, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) { $found = true; break; } } } if ( $found ) { // Loop through country codes foreach ( $countries as $key => $country ) { // NOT found if ( ! in_array( $key, $show_countries ) ) { // Remove unset( $countries[$key] ); } } } } return $countries; } add_filter( 'woocommerce_countries_allowed_countries', 'ts_countries_allowed_countries', 10, 1 );
Output
When the customer visits the checkout page and the cart contains a product with ID 96, the allowed countries will be filtered to include only ‘IN’, ‘NL’, ‘FR’, and ‘ES’ on the dropdown as shown below.
Similarly, you can also restrict billing to a particular country on the WooCommerce checkout page.