Показать или скрыть способы доставки на основе метаданных пользователя в WooCommerce
У меня есть код, чтобы скрыть доставку для неоптовых клиентов, пожалуйста, помогите мне переделать его, мне нужно скрыть вариант доставки для оптовых клиентов.
/**
* Removes shipping methods for non-wholesale customers.
* Please be sure to clear your WooCommerce store's cache.
* Adjust 'flat_rate:2' to match that of your wholesale shipping method.
*/
function my_wcs_remove_shipping_non_wholesale( $rates, $package ){
global $current_user;
$is_wholesale = get_user_meta( $current_user->ID, 'wcs_wholesale_customer', true );
if ( ! $is_wholesale ) {
foreach( $rates as $method ) {
if ( $method->id == 'flat_rate:2' ) {
unset( $rates[$method->id] );
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'my_wcs_remove_shipping_non_wholesale', 10, 2 );
2 ответа
Решение
Вам не нужно иметь 2 функции, одну для оптовых клиентов, а другую для неоптовых клиентов... вы можете объединить обе функции в одной функции следующим образом:
add_filter( 'woocommerce_package_rates', 'shipping_methods_based_on_wholesale_customer', 10, 2 );
function shipping_methods_based_on_wholesale_customer( $rates, $package ){
$is_wholesale = get_user_meta( get_current_user_id(), 'wcs_wholesale_customer', true );
// Set the shipping methods rate ids in the arrays:
if( $is_wholesale ) {
$shipping_rates_ids = array('flat_rate:1', 'flat_rate:4'); // To be removed for NON Wholesale users
} else {
$shipping_rates_ids = array('flat_rate:2'); // To be removed for Wholesale users
}
// Loop through shipping rates fro the current shipping package
foreach( $rates as $rate_key => $rate ) {
if ( in_array( $rate_key, $shipping_rates_ids) ) {
unset( $rates[$rate_key] );
}
}
return $rates;
}
Код находится в файле functions.php активной дочерней темы (или активной темы). Должно работать.
Не забудьте очистить корзину после сохранения кода, чтобы обновить кешированные данные о доставке.
Так что для всех, как я, где код не работал. С помощью @Howard E вот скорректированный код 2022, который теперь работает:
add_filter( 'woocommerce_package_rates', 'shipping_methods_based_on_wholesale_customer', 10, 2 );
function shipping_methods_based_on_wholesale_customer( $rates, $package ) {
$user = wp_get_current_user();
$roles = (array) $user->roles;
// Set the shipping methods rate ids in the arrays.
if ( ! in_array( 'wholesale_customer', $roles, true ) ) {
$shipping_rates_ids = array( 'flat_rate:10', 'flat_rate:7' ); // To be removed for NON Wholesale users.
} else {
$shipping_rates_ids = array( 'flat_rate:13', 'flat_rate:15' ); // To be removed for Wholesale users.
}
// Loop through shipping rates from the current shipping package.
foreach ( $rates as $rate_key => $rate ) {
if ( in_array( $rate_key, $shipping_rates_ids, true ) ) {
unset( $rates[ $rate_key ] );
}
}
return $rates;
}