Answer the question
In order to leave comments, you need to log in
How to write a woocommerce discount system yourself?
Good day, tell me how you can write your own discount system in woocommerce.
None of the plugins meet my needs, because the discount depends on many factors:
- delivery method
- the discount does not apply to all products
- different discount percentages apply for different options of variable products
- on the cart page, the user himself must choose which promotion he takes part
in. I work with woocommerce and wordpress for the first time, so I ask You prompt me to think where I should dig, in which direction to think, or maybe tell me the algorithm for building such systems.
Thanks a lot for any answer!
Answer the question
In order to leave comments, you need to log in
I think you should look towards the woocommerce_cart_calculate_fees hook. There are enough examples of its use on the net. And In the handler of this hook, combine the conditions and recalculate the discount. I also think it's worth looking in the direction of coupons. This is standard Woocommerce functionality. You can combine the conditions of the previous hook and coupons.
/************************************************************************/
/************************************************************************/
/*
* Добавляем возможность скидки 50% на второй (самый дешевый) товар к корзине
* только для товаров категории $category_id = 914; // slag = 'aktsiya-2-1'
*/
add_action( 'woocommerce_cart_calculate_fees','hml_fee_two_plus_one', 10, 1 );
function hml_fee_two_plus_one( WC_Cart $cart_object ) {
global $wpdb, $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { return; }
$arr_cart = $cart_object->get_cart();
if ( 0 == sizeof($arr_cart) ) { return; }
//if ( is_user_logged_in() ) {
// $customer_id = get_current_user_id();
//}
//if ( 1 == $customer_id ) { // only for admin
$count = 0;
$min_price = 0;
$category_id = 914; // slag = 'aktsiya-2-1'
$cats = hml_get_category_gender_line( $category_id ); // смотри ниже
foreach( $arr_cart as $item_key => $value ) {
if ( has_term($cats, 'product_cat', $value['product_id'] ) ) {
$count += $value["quantity"];
$product = $value['data'];
$price = $product->get_price();
if ( $price ) { $prices[] = floatval($price); }
}
}
$min_price = max( $min_price, min($prices) );
if ( $count >= 2 && $min_price > 0 ) {
$fee = -1 * $min_price/2;
$cart_object->add_fee( __('Акция: 2я вещь -50%'), $fee );
}
//}
}
// получаем массив всех вложенных категорий
function hml_get_category_gender_line( $cat_parent ){
// get_term_children() accepts integer ID only
$line = get_term_children( (int) $cat_parent, 'product_cat');
$line[] = $cat_parent;
return $line;
}
/************************************************************************/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question