Скрыть параметры доставки Woocommerce
Поэтому я пытаюсь скрыть определенные методы доставки в Woocommerce на основе тега продукта. Основная проблема, с которой я сталкиваюсь, - это мое собственное отсутствие знаний PHP, поэтому я откликнулся на следующий код вместе с некоторыми очень дружелюбными людьми:
add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_tag' , 10, 1 );
function check_cart_for_share() {
// load the contents of the cart into an array.
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the tag you set. Switch to true if the tag is found.
foreach ($cart as $array_item) {
if (isset($array_item['product_tag']) && $array_item['product_tag'] == "CHOSEN_TAG") { // Replace "CHOSEN_TAG" with what ever tag you want
$found = true;
break;
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function abve to check the cart for the tag.
if ( check_cart_for_share() ) {
// remove the rate you want
unset( $available_methods['flat_rate'] ); // Replace "flar_rate" with the shipping option that yu want to remove.
}
// return the available methods without the one you unset.
return $available_methods;
}
Я понимаю, что этот код ни в коем случае не универсален, и поэтому переменные будут отличаться от случая к случаю, но, возможно, кто-то может сказать мне, если что-то не так в коде. Очень признателен
3 ответа
Без сомнения, вы уже разобрали это, но ваш код стал для меня хорошим началом... и, поскольку я разобрал его, я опубликовал его ниже. Ваша проблема заключалась в том, что у woocommerce нет массива product_tag в массиве корзины, поэтому вам нужно пойти и получить его.
/* !Hide Shipping Options Woocommerce */
add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_tag' , 10, 1 );
function check_cart_for_share() {
// load the contents of the cart into an array.
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the tag you set. Switch to true if the tag is found.
foreach ($cart as $array_item) {
$term_list = wp_get_post_terms( $array_item['product_id'], 'product_tag', array( "fields" => "names" ) );
if (in_array("Heavy",$term_list)) { // Replace "Heavy" with what ever tag you want
$found = true;
break;
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function above to check the cart for the tag.
if ( check_cart_for_share() ) {
// remove the rate you want
unset( $available_methods['flat_rate'] ); // Replace "flat_rate" with the shipping option that you want to remove.
}
// return the available methods without the one you unset.
return $available_methods;
}
Вы можете использовать класс доставки Woocommerce, чтобы достичь этого.
Вот пошаговая инструкция.
- Создайте класс доставки (WooCommerce-> Настройки-> Доставка-> Классы доставки).
- Свяжите этот класс доставки с продуктами (для которых вы хотите скрыть способы доставки)
- Используйте этот фрагмент. (скопируйте и вставьте в файл function.php).
Для получения дополнительной информации о фрагменте доступен здесь.
Используйте его в functions.php вашей темы или создайте плагин с этим кодом.