Мне нужна помощь, чтобы совместить стоимость индивидуальной доставки со скидкой на товары в корзине в WooCommerce.
В приведенном ниже коде первая функция отвечает за добавление скидки 50 % в зависимости от выбранный вариант доставки и
второй отвечает за расчет скидки 50% на каждый товар в корзине, кроме конкретной категории (и ее подкатегорий).
Хотелось бы чтобы при выборе доставки «Самовывоз» покупателем отображалась скидка «-50%», которая добавляется только на товары, не включенные в конкретную категорию и ее подкатегории (для основного идентификатора категории 37).
Первая функция:
add_filter('woocommerce_package_rates', 'local_pickup_percentage_discount', 12, 2);
function local_pickup_percentage_discount( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// HERE define the discount percentage
$percentage = 50; // 50%
$subtotal = WC()->cart->get_subtotal();
// Loop through the shipping taxes array
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
// Targeting "Local pickup"
if( 'local_pickup' === $rate->method_id ){
// Add the Percentage to the label name (optional
$rates[$rate_key]->label .= ' ( - ' . $percentage . '% )';
// Get the initial cost
$initial_cost = $new_cost = $rates[$rate_key]->cost;
// Calculate new cost
$new_cost = -$subtotal * $percentage / 100;
// Set the new cost
$rates[$rate_key]->cost = $new_cost;
// Taxes rate cost (if enabled)
$taxes = [];
// Loop through the shipping taxes array (as they can be many)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 ){
// Get the initial tax cost
$initial_tax_cost = $new_tax_cost = $rates[$rate_key]->taxes[$key];
// Get the tax rate conversion
$tax_rate = $initial_tax_cost / $initial_cost;
// Set the new tax cost
$taxes[$key] = $new_cost * $tax_rate;
$has_taxes = true; // Enabling tax
}
}
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
И второй:add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_price', 10, 1 );
function custom_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$parent_id = 37; // premium-rolls id
$taxonomy = 'product_cat';
foreach ( $cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
$terms_ids = get_term_children( $parent_id, $taxonomy, $product_id ); // get children terms ids array
array_unshift( $terms_ids, $parent_id ); // insert parent term id to children terms ids array
if ( ! has_term( $terms_ids, $taxonomy, $product_id ) ){
$new_price = $cart_item['data']->get_price() / 2; // Get 50% of the initial product price
$cart_item['data']->set_price( $new_price ); // Set the new price
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/648 ... woocommerc
Объедините скидку на доставку со скидкой на товары в корзине в WooCommerce. ⇐ Jquery
Программирование на jquery
1716315236
Anonymous
Мне нужна помощь, чтобы совместить стоимость индивидуальной доставки со скидкой на товары в корзине в WooCommerce.
В приведенном ниже коде первая функция отвечает за добавление скидки 50 % в зависимости от выбранный вариант доставки и
второй отвечает за расчет скидки 50% на каждый товар в корзине, кроме конкретной категории (и ее подкатегорий).
Хотелось бы чтобы при выборе доставки «Самовывоз» покупателем отображалась скидка «-50%», которая добавляется только на товары, не включенные в конкретную категорию и ее подкатегории (для основного идентификатора категории [b]37[/b]).
Первая функция:
add_filter('woocommerce_package_rates', 'local_pickup_percentage_discount', 12, 2);
function local_pickup_percentage_discount( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// HERE define the discount percentage
$percentage = 50; // 50%
$subtotal = WC()->cart->get_subtotal();
// Loop through the shipping taxes array
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
// Targeting "Local pickup"
if( 'local_pickup' === $rate->method_id ){
// Add the Percentage to the label name (optional
$rates[$rate_key]->label .= ' ( - ' . $percentage . '% )';
// Get the initial cost
$initial_cost = $new_cost = $rates[$rate_key]->cost;
// Calculate new cost
$new_cost = -$subtotal * $percentage / 100;
// Set the new cost
$rates[$rate_key]->cost = $new_cost;
// Taxes rate cost (if enabled)
$taxes = [];
// Loop through the shipping taxes array (as they can be many)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 ){
// Get the initial tax cost
$initial_tax_cost = $new_tax_cost = $rates[$rate_key]->taxes[$key];
// Get the tax rate conversion
$tax_rate = $initial_tax_cost / $initial_cost;
// Set the new tax cost
$taxes[$key] = $new_cost * $tax_rate;
$has_taxes = true; // Enabling tax
}
}
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
И второй:add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_price', 10, 1 );
function custom_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$parent_id = 37; // premium-rolls id
$taxonomy = 'product_cat';
foreach ( $cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
$terms_ids = get_term_children( $parent_id, $taxonomy, $product_id ); // get children terms ids array
array_unshift( $terms_ids, $parent_id ); // insert parent term id to children terms ids array
if ( ! has_term( $terms_ids, $taxonomy, $product_id ) ){
$new_price = $cart_item['data']->get_price() / 2; // Get 50% of the initial product price
$cart_item['data']->set_price( $new_price ); // Set the new price
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/64849601/combine-discounted-shipping-cost-with-discounted-cart-items-prices-in-woocommerc[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия