Skip to content

Instantly share code, notes, and snippets.

@artikus11
Last active January 12, 2022 16:17
Show Gist options
  • Save artikus11/d514f2055eb143da2409810025a7e04a to your computer and use it in GitHub Desktop.
Save artikus11/d514f2055eb143da2409810025a7e04a to your computer and use it in GitHub Desktop.
Автоматическое применение купона, если в корзине есть товары из определенной категории
/**
* Автоматическое применение купона, если в корзине есть товары из определенной категории
*
* @testedwith WooCommerce 6.0
* @author Artem Abramovich
*/
function art_apply_matched_is_category() {
// Код купона
$coupon_code = 'vamkover';
$coupon_code = wc_format_coupon_code( $coupon_code );
// ID категории, по которой проверяем присвоение купона
$cats_ids = [ 7 ];
// Получаем все дочерние категории
$cats_ids = array_merge( $cats_ids, get_term_children( 7, 'product_cat' ) );
$apply = false;
$cats = [];
// Находим все категориии у товаров в корзине
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = $cart_item['data'];
$cats[] = $_product->get_category_ids();
}
// Проверяем найденные категории
foreach ( $cats_ids as $cat_id ) {
if ( in_array( $cat_id, array_merge( ...$cats ), true ) ) {
$apply = true;
}
}
// Присваиваем купон
if ( $apply ) {
if ( ! WC()->cart->has_discount( $coupon_code ) ) {
WC()->cart->apply_coupon( $coupon_code );
}
} else {
WC()->cart->remove_coupons( $coupon_code );
}
wc_print_notices();
WC()->cart->calculate_totals();
}
add_action( 'woocommerce_before_cart_table', 'art_apply_matched_is_category' );
/**
* Вывод скидки по купону у цены каждого товара, в зависимости от категории
*
* @param $price
* @param $product
*
* @return string
*
* @testedwith WooCommerce 6.0
* @author Artem Abramovich
*/
function art_add_discount_in_price( $price, $product ) {
// Применненный купон
$applied_coupons = WC()->cart->get_applied_coupons();
// Все купоны
$coupons = WC()->cart->get_coupons();
$coupon_amount = 0;
// Категории у товаров из которых надо выводить скидку
$cats_ids = [ 445 ];
$cats_ids = array_merge( $cats_ids, get_term_children( 7, 'product_cat' ) );
// Находим значения купона
foreach ( $coupons as $code => $coupon ) {
if ( 'percent' === $coupon->get_discount_type() ) {
$coupon_amount += (int) $coupon->get_amount();
}
}
// Проверяем, что товар в нужной категории, считаем и выводим скидку
if ( is_object_in_term( $product->get_id(), 'product_cat', $cats_ids )
&& $coupon_amount
&& WC()->cart->has_discount( array_shift( $applied_coupons ) )
) {
$price = $product->get_price();
$price_coupon = $price - $price * ( $coupon_amount / 100 );
return wc_format_sale_price( $price, $price_coupon ) . $product->get_price_suffix();
}
return $price;
}
add_filter( 'woocommerce_cart_product_price', 'art_add_discount_in_price', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment