When conditions match (specific product IDs and other countries), this code will replace the add to cart buttons in shop archives by a link to the product and in single product pages by a custom text.
You just need to set in:
- 1st function the needed country code … (for you 'US' and already done)
- 2nd and 3rd functions your product IDs in the array
Here is the code:
// Conditional function country code detection
// @argument $code (string): country code restriction
// @return boolean
if( ! function_exists('is_from_country_code') ){
// ==> HERE below set your country code (Replace 'US' by yours)
function is_from_country_code( $code = 'US' ){
$location = new WC_Geolocation;
$user_ip = $location->get_ip_address();
$user_country_code = $location->geolocate_ip( $user_ip, false, false )['country'];
return $user_country_code == $code ? true : false;
}
}
// Replace "Add to cart" single product button and quantity by a custom text
add_action( 'woocommerce_single_product_summary', 'Custom_single_add_to_cart', 1 );
function Custom_single_add_to_cart(){
global $product;
// Set here your product IDS
$product_ids = array( 56, 53, 50 );
if( is_from_country_code() ||
( ! is_from_country_code() && ! in_array( $product->get_id(), $product_ids) ) )
return; // Continue for foreign countries and the specific products IDs
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
add_action('woocommerce_single_product_summary', function(){
echo '<p class="custom-text">'.__('Not available for your country', 'woocommerce').'</p>';
}, 30);
}
// Shop and archives pages: we replace the button add to cart by a link to the product
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_text_replace_button', 10, 2 );
function custom_text_replace_button( $button, $product ) {
// Set here your product IDS
$product_ids = array( 56, 53, 50 );
if( is_from_country_code() ||
( ! is_from_country_code() && ! in_array( $product->get_id(), $product_ids) ) )
return $button; // Continue for foreign countries and the specific products IDs
$button_text = __("View product", "woocommerce");
return '<a class="button" href="'.$product->get_permalink().'">'.$button_text.'</a>';
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested on woocommerce version 3+ and works