Отображать пользовательское сообщение в зависимости от зоны доставки клиентов в Woocommerce.
В woocommerce мне нужно отображать пользовательское сообщение на странице корзины или оформления заказа, в зависимости от зоны доставки, например, "с этого почтового индекса будет взиматься на 10% больше".
Я чувствую, что это легко, но я не могу заставить это работать! И это сводит меня с ума! Любая помощь приветствуется.
Мой обходной путь заключается в настройке такого сообщения по умолчанию:
add_filter( 'woocommerce_no_shipping_available_html', 'wf_customize_default_message', 10, 1 );
// For Checkout page
add_filter( 'woocommerce_cart_no_shipping_available_html', 'wf_customize_default_message', 10, 1 );
function wf_customize_default_message( $default_msg ) {
$zip_array = array(
'30031',
);
if ( in_array( WC()->customer->get_shipping_postcode() , $zip_array) ) {
$custom_msg = "Call us for quotation - 1-800-XXX-XXXX";
if( empty( $custom_msg ) ) {
return $default_msg;
}
return $custom_msg;
}
return $default_msg;
}
2 ответа
обновленный
Попробуйте следующий код, основанный на названии зон доставки (с ограничениями на почтовые индексы), который будет отображать ваше сообщение в строках итоговых отгрузок (но не будет генерировать уведомление woocommerce):
add_action( 'woocommerce_cart_totals_after_shipping' , 'shipping_zone_targeted_postcodes_custom_notice' );
add_action( 'woocommerce_review_order_after_shipping' , 'shipping_zone_targeted_postcodes_custom_notice' );
function shipping_zone_targeted_postcodes_custom_notice() {
// HERE DEFINE YOUR SHIPPING ZONE NAME(S)
$targeted_zones_names = array('France'); // <====== <====== <====== <====== <======
// Get the customer shipping zone name
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod
$chosen_method = explode(':', reset($chosen_methods) );
$shipping_zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );
$current_zone_name = $shipping_zone->get_zone_name();
if( in_array( $current_zone_name, $targeted_zones_names ) ){
echo '<tr class="shipping">
<td colspan="2" style="text-align:center">' . sprintf(
__( "You'll be charged %s more for %s zip code", "woocommerce"),
'<strong>10%</strong>',
'<strong>' . WC()->customer->get_shipping_postcode() . '</strong>'
) . '</td>
</tr>';
}
}
Код помещается в файл function.php вашей активной дочерней темы (или активной темы). Проверено и работает.
Используя решение @LoicTheAztec, описанное выше, я изменил его, чтобы он отображал сообщение в зависимости от страны клиента.
add_action( 'woocommerce_cart_totals_after_shipping' , 'out_of_zone_shipping_notice' );
add_action( 'woocommerce_review_order_after_shipping' , 'out_of_zone_shipping_notice' );
function out_of_zone_shipping_notice() {
// HERE DEFINE YOUR SHIPPING COUNTRY NAMES
$targeted_country_names = array("CA", "US"); //
// Get the customer shipping country
$shipping_country = WC()->customer->get_shipping_country();
if( !in_array( $shipping_country, $targeted_country_names ) ){
echo '<tr class="shipping"><td colspan="2" style="text-align:center">You are outside of our regular shipping zone. Please <a href="../contact/">contact us</a> with your address so we can get an accurate cost to ship.</td></tr>';
}
}
Чтобы увидеть, в каком формате отображается $ shipping_country, я использовал
echo $shipping_country
чуть ниже $ shipping_country = WC () ->customer->get_country(); чтобы показать на странице корзины, каков был фактический синтаксис кода страны, чтобы я мог сопоставить его с оператором if . Однако этот сегмент кода был удален перед развертыванием, чтобы на экране не появлялись случайные символы для клиента.