[Special Summer Sale] 40% OFF All Magento 2 Themes

Cart

Change product price based on customer billing country in WooCommerce

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #9918
    carl
    Participant

    I need to change the currency depending on the billing country, with the following code it is possible in a certain way, but it only works with simple products, not with variable ones.

    add_filter('woocommerce_get_price', 'return_custom_price', $product, 2);
    
    function return_custom_price($price, $product) {    
        global $post, $woocommerce;
        
        // Array containing country codes
        $county = array('US');
        // Amount to increase by
        //$amount = 5;
        // If the custromers shipping country is in the array
        if ( in_array( $woocommerce->customer->get_billing_country(), $county ) && is_checkout() ){
            // Return the price plus the $amount
           return $new_price = ($price/260)*1.25;
        } else {
             
            // Otherwise just return the normal price
            return $price;
        }
    } 
    
    #9919
    loictheaztec
    Participant

    The hook woocommerce_get_price is obsolete and deprecated since WooCommerce 3 and has been replaced with the following hooks:

    • woocommerce_product_get_price (for products)
    • woocommerce_product_variation_get_price (for variations of a variable product).

    There are some other mistakes in your code. Try the following revised code:

    add_filter('woocommerce_product_get_price', 'country_based_cart_item_price', 100, 2);
    add_filter('woocommerce_product_variation_get_price', 'country_based_cart_item_price', 100, 2);
    
    function country_based_cart_item_price( $price, $product ) {    
        // Define below in the array the desired country codes
        $targeted_countries = array('US');
        $billing_country    = WC()->customer->get_billing_country();
    
        // Only on cart and checkout pages 
        if ( ( is_checkout() || is_cart() ) && in_array($billing_country, $targeted_countries) ){
            // Returns changed price
           return $price / 260 * 1.25;
        }
        return $price;
    } 
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    See: Change product prices via a hook in WooCommerce 3+

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.