基于购物车项目的Woocommerce条件类别折扣

时间:2020-05-27 14:34:21

标签: php wordpress woocommerce

我已成功组合代码以根据购物车中的商品对类别应用不同的折扣。下面的代码显示了如果购物篮中有来自“汽车”类别的产品,则如何应用折扣。然后将个人折扣应用于“自行车”(-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>';
}

0 个答案:

没有答案