Удалить Канаду из списка стран, когда определенные продукты есть в корзине на Woocommerce

Я хочу сделать что-то простое: не отправлять конкретный продукт в Канаду.

Вот самый простой способ сделать это, по моему мнению: если этот конкретный продукт присутствует в корзине, удалите Канаду со страницы оформления заказа.

Особые продукты:
1- https://constructioncovers.com/product/insulated-cement-curing-blankets/ (ID: 12616)
2- https://constructioncovers.com/product/insulated-construction-tarps/ (ID: 15631)

Мое исследование:
Эта статья дала мне возможность найти товары в корзине и выполнить любое действие, если условие выполняется: https://businessbloomer.com/woocommerce-easily-check-product-id-cart/ Эта статья дала мне возможность удалить определенную страну со страницы оформления заказа Как удалить конкретную страну в WooCommerce Я объединил и изменил два кода, чтобы попытаться выполнить мою задачу. Вот мой код:

function unset_country_on_condition( $country ) {
$product_id = 15631;
$product_id_2 = 12616;
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$product_cart_id_2 = WC()->cart->generate_cart_id( $product_id_2 );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
$in_cart_2 = WC()->cart->find_product_in_cart( $product_cart_id_2 );
if ( $in_cart || $in_cart_2 ) {
unset($country["CA"]);
return $country;
}
}
add_filter( 'woocommerce_countries', 'unset_country_on_condition', 10, 1 );

Но вышеуказанная функция не работает
. Это делает раскрывающийся список страны пустым, что приводит к предупреждению по всему сайту.

Может кто-то указать, что я делаю не так?

Скриншоты:
введите описание изображения здесь
введите описание изображения здесь

1

Решение

Следующий код удалит «Канада» из разрешенных стран, когда определенные продукты находятся в корзине:

add_filter( 'woocommerce_countries', 'products_disable_country', 10, 1 );
function products_disable_country( $countries ) {
if( is_cart() || is_checkout() ) {

$products = array(15631, 12616);

foreach( WC()->cart->get_cart() as $item ){
if( in_array( $item['product_id'], $products ) ){
unset($countries["CA"]);
return $countries;
}
}
}

return $countries;
}

Код помещается в файл function.php вашей активной дочерней темы (active theme). проверено и работает.

1

Другие решения

Отредактировано от этот ответ

   add_filter( 'woocommerce_countries', 'unset_country_on_condition', 10, 1 );
function unset_country_on_condition( $countries ) {

// Set here your to add product IDS (in the array)
$product_ids = array( 15631, 12616 );
$is_in_cart = false;

// Iterating through cart items and check
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item )
if( in_array( $cart_item['data']->get_id(), $product_ids ) ){
$is_in_cart = true; // We set it to "true"break; // At least one product, we stop the loop
}

if( $is_in_cart ){
unset($countries["CA"]);
}
return $countries;
}
1

Можете ли вы попробовать следующий код.

global $product_check; //declare a global variable
function remove_canada_insulated_blankets_traps(){
$product_ids = array(12616,15631);
foreach($product_ids as $product_id){
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
$product_check[$in_cart]; //global variable is converted into an array storing ids
}
}
add_action( 'woocommerce_before_cart', 'remove_canada_insulated_blankets_traps' );

//pass the global variable into following function as another argument
function woo_remove_canada_country( $countries, $product_check ){
if( count(product_check) > 0 ){ //check count of the array
unset($countries['CA']); //unset country
}
return $countries;
}
add_filter( 'woocommerce_countries', 'woo_remove_canada_country', 10, 2 );

Обратите внимание на изменение последнего аргумента фильтра ‘woocommerce_countries’. Поскольку дополнительный аргумент передается функции, последний аргумент изменяется на 2 вместо 1.

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector