我正在使用以下代码将 WooCommerce 帐单国家/地区更改为所选的网站语言。
add_filter('init', function() {
$lang = apply_filters( 'wpml_current_language', NULL );
$lang = strtoupper($lang);
WC()->customer->set_country( $lang );
});
代码有效,但仅在加载购物车或结账页面时有效。我想要实现的目标是在客户登陆的第一页上更改帐单国家/地区,而不仅仅是在购物车或结帐页面上。
税费和货币根据帐单所在国家/地区计算。因此,当客户选择不同的语言时,我希望这两者随之改变。
有谁知道我怎样才能实现这个目标?
请注意,
WC_Customer
方法set_country()
不存在(在此处检查)。
相反,您需要使用
WC_Customer
方法 set_billing_country()
(或/和 set_shipping_country()
).
为了让此代码有效工作,您需要确保客户会话已启动。
假设您从 WPML 当前语言获取正确的国家/地区代码,请尝试以下修改后的代码:
add_action( 'init', 'set_billing_country_from_wpml_current_language' );
function set_billing_country_from_wpml_current_language(){
// Not on backend
if ( is_admin() ) {
return;
}
// Early enable customer session
if ( isset(WC()->session) && ! WC()->session->has_session() ) {
WC()->session->set_customer_session_cookie( true );
}
// Get the country code from current language
$country_code = strtoupper( apply_filters( 'wpml_current_language', NULL ) );
// Test that you get the correct country code (enabling WP_DEBUG)
// error_log( "Country code from WPML language: {$country_code}" );
if ( WC()->customer->get_billing_country() !== $country_code )
// Set customer Billing country
WC()->customer->set_billing_country( $country_code );
}
}
它应该可以工作(未经测试)。
如果需要,您可以尝试启用 WP_Debug 如此处所述,以检查您是否获得了正确的国家/地区代码。
补充:
您还可以尝试将帐单国家/地区代码更改为“客户”
WC_Session
,例如:
// Get customer data from session
$customer = WC()->session->get('customer');
if ( $customer['country'] !== $country_code ) {
// Change the country code from billing country
$customer['country'] = $country_code;
// Set back the data
WC()->session->set('customer', $customer);
}