Automatic 10% Discount for Category Products

Beginner
✓ Tested
📅 September 20, 2025
⬇️ 0 Downloads
📋 0 Copies

This simple snippet automatically applies a 10% discount to all products from a specific category when they’re added to the cart. No coupon codes needed – the discount is applied automatically and customers can see it clearly.

What does this code do?

The snippet monitors the shopping cart and automatically reduces prices by 10% for any products that belong to category ID 33. The discount is visible in the cart, on product pages, and as badges in the shop.

Features:

  • Automatic 10% discount on category 33 products
  • No coupon codes required
  • Discount notice in cart
  • Product page discount info
  • Discount badges in shop/category pages
  • Admin notices showing active discount
  • Mobile responsive design

Visual elements:

  • Green success notice in cart
  • Dashed border info box on product pages
  • Red discount badges on product images
  • Admin notice in product pages

Where discount appears:

  • Cart page with reduced prices
  • Checkout page with discounted totals
  • Product pages with discount notice
  • Shop pages with discount badges
  • Category pages with visual indicators

⚠️ Important Warnings

⚠️ Always backup before adding discount code
⚠️ Test thoroughly with different product combinations
⚠️ Discount applies to regular price, not sale price
⚠️ May conflict with other discount plugins or coupons
⚠️ Check tax calculations with discounted prices
⚠️ Some payment gateways might need testing with discounts
⚠️ Ensure category ID exists and has products
⚠️ Clear any caching after implementing
💻 PHP Code
/**
 * Automatic 10% discount for products from specific category
 * Apply discount automatically when products added to cart
 * Prefix: tpsc_ (TP Snippet Collection)
 */

// ============================================
// CONFIGURATION
// ============================================

// Set your category IDs here (can add multiple categories)
define('TPSC_DISCOUNT_CATEGORIES', array(33, 45, 67, 89));

// Set discount percentage (10 = 10%)
define('TPSC_DISCOUNT_PERCENTAGE', 10);

// Set discount name (appears in cart)
define('TPSC_DISCOUNT_NAME', 'Category Discount (10%)');

// ============================================
// APPLY AUTOMATIC DISCOUNT
// ============================================

// Apply discount when cart is updated
add_action('woocommerce_before_calculate_totals', 'tpsc_apply_category_discount');
function tpsc_apply_category_discount($cart) {
    
    // Exit if we're in admin or during AJAX requests (except cart updates)
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }
    
    // Avoid infinite loops during calculations
    if (did_action('woocommerce_before_calculate_totals') >= 2) {
        return;
    }
    
    // Check if cart is empty
    if ($cart->is_empty()) {
        return;
    }
    
    // Loop through cart items
    foreach ($cart->get_cart() as $cart_item) {
        $product = $cart_item['data'];
        $product_id = $cart_item['product_id'];
        
        // Check if product is in the discount category
        if (tpsc_product_in_discount_category($product_id)) {
            
            // Get original price
            $original_price = $product->get_regular_price();
            if (empty($original_price)) {
                $original_price = $product->get_price();
            }
            
            // Calculate discounted price
            $discount_amount = ($original_price * TPSC_DISCOUNT_PERCENTAGE) / 100;
            $new_price = $original_price - $discount_amount;
            
            // Set new price
            $product->set_price($new_price);
        }
    }
}

// ============================================
// HELPER FUNCTIONS
// ============================================

// Check if product belongs to discount category
function tpsc_product_in_discount_category($product_id) {
    $product_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
    
    if (is_wp_error($product_categories) || empty($product_categories)) {
        return false;
    }
    
    // Check if product is in any of the discount categories
    $discount_categories = TPSC_DISCOUNT_CATEGORIES;
    return array_intersect($discount_categories, $product_categories);
}

// ============================================
// DISPLAY DISCOUNT INFO
// ============================================

// Add discount notice in cart
add_action('woocommerce_before_cart_table', 'tpsc_display_cart_discount_notice');
function tpsc_display_cart_discount_notice() {
    
    $has_discount_products = false;
    
    // Check if cart has products from discount category
    foreach (WC()->cart->get_cart() as $cart_item) {
        if (tpsc_product_in_discount_category($cart_item['product_id'])) {
            $has_discount_products = true;
            break;
        }
    }
    
    if ($has_discount_products) {
        echo '<div class="woocommerce-info tpsc-discount-notice">';
        echo '<strong>🎉 ' . TPSC_DISCOUNT_NAME . ' Applied!</strong><br>';
        echo 'Selected products have automatically received a ' . TPSC_DISCOUNT_PERCENTAGE . '% discount.';
        echo '</div>';
    }
}

// ============================================
// PRODUCT PAGE DISCOUNT INFO
// ============================================

// Show discount info on product page
add_action('woocommerce_single_product_summary', 'tpsc_display_product_discount_info', 25);
function tpsc_display_product_discount_info() {
    global $product;
    
    if (!$product) {
        return;
    }
    
    // Check if current product is in discount category
    if (tpsc_product_in_discount_category($product->get_id())) {
        echo '<div class="tpsc-product-discount-info">';
        echo '<p style="color: #27ae60; font-weight: bold; margin: 10px 0;">';
        echo '🎉 This product gets an automatic ' . TPSC_DISCOUNT_PERCENTAGE . '% discount in cart!';
        echo '</p>';
        echo '</div>';
    }
}

// ============================================
// SHOP PAGE DISCOUNT BADGES
// ============================================

// Add discount badge to products in shop/category pages
add_action('woocommerce_before_shop_loop_item_title', 'tpsc_add_discount_badge', 15);
function tpsc_add_discount_badge() {
    global $product;
    
    if (!$product) {
        return;
    }
    
    // Check if product is in discount category
    if (tpsc_product_in_discount_category($product->get_id())) {
        echo '<div class="tpsc-discount-badge">';
        echo TPSC_DISCOUNT_PERCENTAGE . '% OFF';
        echo '</div>';
    }
}

// ============================================
// STYLING
// ============================================

// Add CSS for discount elements
add_action('wp_head', 'tpsc_discount_styles');
function tpsc_discount_styles() {
    echo '<style>
        .tpsc-discount-notice {
            background-color: #d4edda !important;
            border-color: #c3e6cb !important;
            color: #155724 !important;
            padding: 15px !important;
            border-radius: 5px !important;
            margin-bottom: 20px !important;
        }
        
        .tpsc-product-discount-info {
            background-color: #f8f9fa;
            border: 2px dashed #27ae60;
            border-radius: 5px;
            padding: 15px;
            margin: 15px 0;
            text-align: center;
        }
        
        .tpsc-discount-badge {
            position: absolute;
            top: 10px;
            left: 10px;
            background-color: #e74c3c;
            color: white;
            padding: 5px 10px;
            font-size: 12px;
            font-weight: bold;
            border-radius: 3px;
            z-index: 1;
            text-transform: uppercase;
        }
        
        .woocommerce ul.products li.product {
            position: relative;
        }
        
        /* Mobile responsive */
        @media (max-width: 768px) {
            .tpsc-discount-badge {
                font-size: 10px;
                padding: 3px 6px;
            }
        }
    </style>';
}

// ============================================
// ADMIN TOOLS
// ============================================

// Add admin notice to show current settings
add_action('admin_notices', 'tpsc_admin_discount_notice');
function tpsc_admin_discount_notice() {
    $screen = get_current_screen();
    
    if ($screen && ($screen->id === 'edit-product' || $screen->id === 'product')) {
        $category_names = array();
        foreach (TPSC_DISCOUNT_CATEGORIES as $cat_id) {
            $category = get_term($cat_id, 'product_cat');
            $category_names[] = $category ? $category->name : 'ID ' . $cat_id;
        }
        
        echo '<div class="notice notice-info">';
        echo '<p><strong>Category Discount Active:</strong> ';
        echo TPSC_DISCOUNT_PERCENTAGE . '% automatic discount for products in: ' . implode(', ', $category_names) . '</p>';
        echo '</div>';
    }
}

📝 Installation Instructions

QUICK START:

Copy the entire code
The discount is set for category ID 33 with 10% off
Paste in functions.php
Add products from category 33 to cart - discount applies automatically!

TO CHANGE CATEGORIES:
Find: define('TPSC_DISCOUNT_CATEGORIES', array(33, 45, 67, 89));
Change the numbers to your category IDs.
Examples:

Single category: array(33)
Two categories: array(33, 45)
Multiple categories: array(33, 45, 67, 89, 123)

To find your category IDs:

Go to Products → Categories
Click on the category you want
Look at the URL: tag_ID=123 (123 is your ID)

TO CHANGE DISCOUNT PERCENTAGE:
Find: define('TPSC_DISCOUNT_PERCENTAGE', 10);
Change 10 to any percentage:

15% discount: change to 15
5% discount: change to 5
25% discount: change to 25

TO CHANGE DISCOUNT NAME:
Find: define('TPSC_DISCOUNT_NAME', 'Category Discount (10%)');
Change to your preferred text:
'Special Sale (10% Off)'
'Member Discount'
'Flash Sale Discount'
TO ADD MORE CATEGORIES LATER:
Just add the category ID to the array:
define('TPSC_DISCOUNT_CATEGORIES', array(33, 45, 67, 89, 123, 456));
TO CHANGE BADGE COLOR:
Find: background-color: #e74c3c;
Change to different colors:

Blue: #3498db
Green: #27ae60
Orange: #f39c12
Purple: #9b59b6

TO REMOVE DISCOUNT BADGES:
Comment out or delete the entire tpsc_add_discount_badge function.
TO CHANGE NOTICE STYLING:
Find the .tpsc-discount-notice CSS section and modify:

Background color
Border color
Text color
Padding/margins

TESTING:

Add a product from category 33 to cart
Check that price is reduced by 10%
Verify discount notice appears in cart
Check product page shows discount info
Look for discount badge in shop
Test with products from other categories

TROUBLESHOOTING:

Discount not applied: Check category ID is correct
No badge showing: Clear cache and check CSS
Wrong percentage: Verify TPSC_DISCOUNT_PERCENTAGE value
Multiple discounts conflict: Check for other discount plugins

📸 Screenshots

💬 Let's Connect and Share!

Got a question about this snippet?

Something not working as expected? Need help customizing it for your specific needs?

💡

Want to request a custom snippet?

Have an idea for functionality you're missing on your site? Tell us what you're looking for!

🤝

Have an awesome snippet you're using?

Share it with us! Our community loves learning and growing together.

No comments yet.

Leave a Comment

Leave a Comment

To leave a comment, please enter your email address. We will send you a verification code to confirm your identity.

Email Verification

We sent a 6-digit verification code to your email address. Please check your inbox and enter the code below:

Write Your Comment

Great! Your email is verified. Now you can write your comment:

Comment Submitted!