Я успешно собрал код для применения различных скидок к категориям в зависимости от товара в корзине. Код ниже показывает, как применяется скидка, ЕСЛИ в корзине находится товар из категории «автомобили». Затем индивидуальные скидки применяются к категориям «велосипеды» (-10%) и «обувь» (-50%).
Я борюсь с тем, как показать цены до и после скидки, много например, обычная цена и цена со скидкой с зачеркиванием обычной цены. Любые идеи будут оценены?
// Discount Rules for all categories outside of 'cars'
add_action('woocommerce_before_cart', 'tc_check_category_in_cart');
add_action('woocommerce_before_single_product', 'tc_check_category_in_cart');
function tc_check_category_in_cart() {
$cat_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( 'cars', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
// Action if category "cars" is in cart
if ( $cat_in_cart ) {
add_filter( 'woocommerce_product_get_price', 'custom_sale_price_for_bikes', 10, 2 );
add_filter( 'woocommerce_product_get_price', 'custom_sale_price_for_shoes', 10, 2 );
add_filter( 'woocommerce_before_single_product_summary', 'tc_discount_message', 10, 2 );
}
}
// Discount Rules for all categories outside of Cars
function custom_sale_price_for_bikes( $price, $product ) {
$terms = wp_get_post_terms( $product->get_id(), 'product_cat' );
foreach ( $terms as $term ) {
$categories[] = $term->slug;
}
if ( ! empty( $categories ) && in_array( 'bikes', $categories, true ) ) {
$price *= ( 1 - 0.10 );
}
return $price;
}
function custom_sale_price_for_shoes( $price, $product ) {
$terms = wp_get_post_terms( $product->get_id(), 'product_cat' );
foreach ( $terms as $term ) {
$categories[] = $term->slug;
}
if ( ! empty( $categories ) && in_array( 'shoes', $categories, true ) ) {
$price *= ( 1 - 0.50 );
}
return $price;
}
// Discount Message to Show
function tc_discount_message() {
echo '<div style="margin: 50px 0px;">YOU CAN NOW GET 10% OFF ALL BIKES & 50% OFF ALL SHOES...</div>';
}