Hello, welcome to therichpost.com. In this post, I will tell you Woocommerce Category Based Discount Hook. WordPress is the best cms and Woocommerce is the best Ecommerce plugin. WordPress hooks(add_action, add_filter) give us the power to edit or change the code without interruption into the files and this is the best thing about wordpress. Now I am going to tell you how the hooks work.
I have used category id in woocommerce hook to add discount.
Here is the working code for Woocommerce Category Based Discount Hook:
// Add Service Fee to Category
function woo_add_cart_fee() {
$category_ID = ’18’;
global $woocommerce;
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
// Get the terms, i.e. category list using the ID of the product
$terms = get_the_terms( $values[‘product_id’], ‘product_cat’ );
// Because a product can have multiple categories, we need to iterate through the list of the products category for a match
foreach ($terms as $term) {
// 18 is the ID of the category for which we want to add discoun
if($term->term_id == $category_ID){
$discount = $woocommerce->cart->subtotal * 0.2;
$woocommerce->cart->add_fee(‘You have products in Cap category, so 20% discount has been added.’, -$discount);
}
}}
}
add_action( ‘woocommerce_cart_calculate_fees’, ‘woo_add_cart_fee’ );
There are so many hooks in wordpress and i will let you know all. Please do comment if you any query related to this post. Thank you. Therichpost.com
Hi,
I have used your code and found a problem. It is adding discounts on the cart level. But, I need to give discount to only products that are in cap category?
How can I do that?
Thanks
https://therichpost.com/making-the-commission-fee-to-be-added-to-the-woocommerce-product-dokan-multivendor-wordpress/