我的代码打破了WooCommerce多语言货币切换器

时间:2016-04-12 15:18:35

标签: php wordpress woocommerce wpml

WPML Woocommerce Multilingual根据用户位置不支持货币设置,因此我们制作了自己的代码:

function geoIPLocator() { 
global $woocommerce_wpml; 

$currency='EUR'; 
$geo=new WC_Geolocation(); 
$geo->init(); 
$country=$geo::geolocate_ip($geo::get_ip_address() ); 

if(isset($_SESSION['locator'])) { 
   if($_SESSION['locator']['IP']= =$_SERVER['REMOTE_ADDR'] && strlen($_SESSION['locator']['IP' ])>0) { 
    $woocommerce_wpml->multi_currency_support->s et_client_currency($_SESSION['locator'][ 'currency']); 

    return; 
   } 
} 

if($country['country']=="RU" || $country['country']=="BY") { 
    $woocommerce_wpml->multi_currency_support->s et_client_currency('RUB'); 
    $currency='RUB'; 
} else { 
    $woocommerce_wpml->multi_currency_support->s et_client_currency('EUR'); 
    $currency='EUR'; 
} 

$_SESSION['locator']=array("IP" =>$_SERVER['REMOTE_ADDR'], "ISO"=>$country['country'], "currency"=>$currency); 
} 

add_action( 'init', 'geoIPLocator', 5); 

问题在于它打破了常规货币切换器。当此代码打开时,我们无法将货币转换为任何其他货币。是因为我们不保存或检查用户是否已经设置了某种货币(如手动切换器那样)?

1 个答案:

答案 0 :(得分:0)

这是更正后的代码

function geoIPLocator() {
   try {
           global $woocommerce;

           if ( isset($woocommerce) && gettype($woocommerce) == 'object' && property_exists($woocommerce,'session') && gettype($woocommerce->session) == 'object' && property_exists($woocommerce->session,'get') ) {
                   $manual_switch=$woocommerce->session->get('client_currency', null);

                   if ( $manual_switch == null ) {

                           global $woocommerce_wpml;

                           $currency='EUR';
                           $geo=new WC_Geolocation();
                           $geo->init();
                           $country=$geo::geolocate_ip($geo::get_ip_address());


                           if(isset($_SESSION['locator'])) {
                                   if($_SESSION['locator']['IP']==$_SERVER['REMOTE_ADDR'] && strlen($_SESSION['locator']['IP'])>0) {
                                           $woocommerce_wpml->multi_currency_support->set_client_currency($_SESSION['locator']['currency']);

                                           return;
                                   }
                           }

           if($country['country']=="RU" || $country['country']=="BY") {
                   $woocommerce_wpml->multi_currency_support->set_client_currency('RUB');
                   $currency='RUB';
           }  
           else {
                   $woocommerce_wpml->multi_currency_support->set_client_currency('EUR');
                   $currency='EUR';
           }

                           $_SESSION['locator']=array("IP"=>$_SERVER['REMOTE_ADDR'], "ISO"=>$country['country'], "currency"=>$currency);
                   }
           }

   } catch (Exception $e) {
           $e->getMessage();
   }

}

add_action( 'init', 'geoIPLocator', 5);