Are you tired of paying $100+ per year for a WooCommerce discount rules plugin? What if you could build your own fully functional, custom discount pricing plugin in under an hour — completely free — using Claude AI? In this step-by-step guide, I will show you exactly how I built a production-ready WooCommerce discount rules plugin from scratch using Claude AI, without needing advanced PHP coding skills. Whether you want percentage discounts, fixed amount discounts, BOGO deals, or cart-total-based pricing rules, this tutorial covers everything you need to create a plugin that works beautifully on your WooCommerce store.
Table of Contents
What Is a WooCommerce Discount Rules Plugin?
A WooCommerce discount rules plugin is a WordPress plugin that allows store owners to create advanced, conditional pricing rules for their WooCommerce shop. Unlike the basic coupon system built into WooCommerce, a discount rules plugin gives you granular control over when, where, and how discounts are applied.
With a discount rules plugin, you can set up pricing conditions such as:
- Apply a 20% discount when a customer’s cart total exceeds $200
- Give a $20 fixed discount on orders above a certain value
- Offer Buy 2 Get 1 Free deals on specific products
- Apply discounts only to specific product categories
- Schedule flash sales with automatic start and end dates
Popular premium plugins like Discount Rules for WooCommerce by Flycart, Advanced Pricing by YayPricing, and WooCommerce Dynamic Pricing charge anywhere from $49 to $299 per year. Our approach builds the same core functionality for free using Claude AI.
Why Build Your Own WooCommerce Discount Rules Plugin Instead of Buying One?
Save Money on Annual Plugin Licenses
Premium WooCommerce pricing plugins come with recurring annual fees. Building your own means you own the code outright with zero ongoing costs. For freelancers, agency owners, and small store owners, that saving compounds year after year.
Full Control Over Features
When you buy a plugin, you get whatever the developer decided to include. When you build your own, you get exactly what you need — no more, no less. No feature bloat, no settings you will never use, and no plugin conflicts from unnecessary code.
No Vendor Lock-In
Third-party plugin developers can change pricing, abandon the plugin, or introduce breaking changes. A plugin you built and own is entirely under your control and can be modified at any time.
Great Learning Experience
Building a plugin with Claude AI teaches you how WooCommerce hooks, filters, and the cart system work — practical knowledge that helps you manage and troubleshoot your store more effectively.
Detailed Prompt to create WooCommerce Discount Rules Plugin Using Claude AI
Create a WooCommerce Discount Rules Plugin for WordPress.
The plugin should be production-ready, fully functional, and installable
as a ZIP file. Follow every instruction below exactly.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
PLUGIN DETAILS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Plugin Name: WC Discount Rules
Version: 1.5.0
Author: Quick Tips
Author URI: https://www.youtube.com/@ParamFreelance
Description: Create powerful, flexible discount rules for WooCommerce.
Text Domain: wc-discount-rules
WC tested up to: 9.0
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
FILE STRUCTURE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Create the following files inside a folder called wc-discount-rules/
and package them into a downloadable ZIP:
wc-discount-rules/
├── wc-discount-rules.php ← Main plugin file
├── includes/
│ ├── class-wcdr-db.php ← Database CRUD
│ ├── class-wcdr-engine.php ← Discount calculation engine
│ └── class-wcdr-admin.php ← Full admin UI
├── admin/
│ ├── css/admin.css ← Admin + frontend styles
│ └── js/admin.js ← Dynamic form behaviour
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
MAIN PLUGIN FILE — wc-discount-rules.php
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
– Define constants: WCDR_VERSION, WCDR_PLUGIN_DIR, WCDR_PLUGIN_URL, WCDR_TABLE (‘wcdr_rules’)
– On plugins_loaded: check WooCommerce is active, then require and init all three classes
– On register_activation_hook: call WCDR_DB::create_table()
– Declare WooCommerce feature compatibility using before_woocommerce_init hook:
– custom_order_tables (HPOS) → true
– cart_checkout_blocks → true
– On wp_enqueue_scripts: enqueue admin/css/admin.css on is_cart() and is_checkout()
pages so the frontend discount line is styled correctly
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DATABASE — class-wcdr-db.php
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Create a custom table {prefix}wcdr_rules using dbDelta() with these columns:
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
rule_name VARCHAR(200)
status TINYINT(1) DEFAULT 1
priority INT DEFAULT 10
discount_type VARCHAR(30) → ‘percentage’, ‘fixed_amount’, ‘fixed_price’, ‘bogo’
discount_value DECIMAL(10,4)
apply_to VARCHAR(30) → ‘all’, ‘products’, ‘categories’
apply_ids LONGTEXT → serialized array of IDs
min_qty INT NULL
max_qty INT NULL
min_cart DECIMAL(10,4) NULL
max_cart DECIMAL(10,4) NULL
user_roles LONGTEXT → serialized (unused but kept for future use)
date_from DATE NULL
date_to DATE NULL
exclusive TINYINT(1) DEFAULT 0
bogo_buy_qty INT NULL
bogo_get_qty INT NULL
bogo_get_discount DECIMAL(10,4) DEFAULT 100
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
Provide these static methods:
– init() → run create_table() if db version option doesn’t match WCDR_VERSION
– create_table() → dbDelta SQL, update wcdr_db_version option
– get_all_rules() → ORDER BY priority ASC, id ASC
– get_active_rules()→ WHERE status = 1 ORDER BY priority ASC, id ASC
– get_rule($id) → single row by id
– save_rule($data) → INSERT or UPDATE based on presence of id field
– delete_rule($id)
– toggle_status($id, $status)
In save_rule(): treat empty string as NULL for min_qty, max_qty, min_cart,
max_cart, bogo_buy_qty, bogo_get_qty fields.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DISCOUNT ENGINE — class-wcdr-engine.php
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Hook: woocommerce_cart_calculate_fees (priority 20)
Hook: woocommerce_cart_totals_fee_html → wrap negative fees in
<span class=”wcdr-discount-line”> for green styling
CRITICAL RULES — follow these exactly or the discount will not work:
1. NEVER call $product->set_price() or mutate product prices in any way.
Always apply discounts as a NEGATIVE FEE using $cart->add_fee().
This is the only stable WooCommerce approach — set_price() compounds
on every recalculation and breaks the cart total.
2. NEVER use wc_price() in a fee label. wc_price() outputs HTML.
WooCommerce strips HTML from fee names (used as internal keys),
which corrupts the label and causes the fee to be silently dropped.
Use plain text only:
$symbol = html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, ‘UTF-8’);
$label = $rule->rule_name . ‘ (‘ . $symbol . number_format($amount, 2) . ‘ off)’;
3. Use get_subtotal() for the cart total check — this hook fires AFTER
WooCommerce has calculated item totals so get_subtotal() is accurate here.
Do NOT manually sum prices×qty as a workaround.
4. In the rule-matching loop, perform ALL condition checks before adding
a rule to $applied_rules:
a) Date range (date_from / date_to)
b) Cart subtotal min/max (min_cart / max_cart)
c) Quantity condition — loop cart items, at least one must satisfy min_qty/max_qty
d) Scope check — if apply_to !== ‘all’, loop cart items and confirm at least
one matches product_matches_scope(). Do this for ALL discount types,
not just bogo/fixed_price.
5. Fee label must be plain text. Build $label_parts[] for each matched rule
and implode with ‘ + ‘ at the end. Cap total_discount at cart subtotal.
DISCOUNT TYPE CALCULATIONS:
– percentage: scoped_subtotal × (discount_value / 100)
scoped_subtotal = sum of (price × qty) for items matching scope only
– fixed_amount: discount_value as a flat amount (e.g. $20 off entire cart)
– fixed_price: per matching item: (unit_price – fixed_price) × qty, summed
– bogo: for each matching item: sets = floor(qty / (buy+get)),
free_qty = sets × get_qty,
discount = free_qty × unit_price × (bogo_get_discount / 100)
SCOPE CHECK — product_matches_scope($product, $rule):
– apply_to = ‘all’ → always true
– apply_to = ‘products’ → product id or parent id in apply_ids array
– apply_to = ‘categories’ → intersection of product’s category IDs and apply_ids
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ADMIN UI — class-wcdr-admin.php
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Register submenu under WooCommerce → Discount Rules (manage_woocommerce cap).
Enqueue on this page only:
– WooCommerce’s own select2 JS and CSS (from WC()->plugin_url())
– admin/css/admin.css
– admin/js/admin.js (depends on jquery, select2)
– wp_localize_script with wcdr object: { ajax_url, nonce: wp_create_nonce(‘wcdr_nonce’) }
Admin POST handlers (check_admin_referer + manage_woocommerce cap):
– wcdr_save_rule → WCDR_DB::save_rule(), redirect with ?saved=1
– wcdr_delete_rule → WCDR_DB::delete_rule(), redirect with ?deleted=1
– wcdr_toggle_rule → WCDR_DB::toggle_status(), redirect back
WP AJAX handlers (wp_ajax_ only, nonce: wcdr_nonce, cap: manage_woocommerce):
– wcdr_search_products → wc_get_products([‘s’=>$term, ‘limit’=>30])
return JSON array of {id, text}
text format: “Product Name (#ID)”
– wcdr_search_categories → get_terms([‘taxonomy’=>’product_cat’,’search’=>$term])
return JSON array of {id, text}
PAGE ROUTER:
– action=list (default) → render rules table
– action=new → render add form
– action=edit&id=X → load rule, render edit form
RULES LIST TABLE columns:
#, Rule Name (+ Exclusive badge if exclusive=1), Type, Discount,
Applies To, Min Cart, Date Range, Priority, Status (toggle button),
Actions (Edit + Delete)
Status toggle: inline form with wcdr_toggle_rule, shows ✅ Active / ⛔ Inactive
ADD/EDIT FORM sections:
1. Basic Settings: rule_name (required), status radio, priority number, exclusive checkbox
2. Discount Settings: discount_type select, discount_value input (hidden when bogo),
bogo row (buy/get/discount inputs, hidden when not bogo)
3. Applies To: apply_to select (all/products/categories),
Select Items row (hidden when all) with #apply_ids select[multiple]
4. Conditions: min_cart/max_cart inputs, min_qty/max_qty inputs
5. Schedule: date_from / date_to date inputs
6. Submit row: “💾 Save Rule” / “💾 Update Rule” button + Cancel link
SELECT ITEMS FIELD — this is critical, do it exactly as follows:
– Render <select id=”apply_ids” name=”apply_ids[]” multiple> with NO static options
– Select2 is initialised in JS with AJAX pointing to wcdr_search_products
or wcdr_search_categories depending on current scope
– minimumInputLength: 0 so results appear on first click without typing
– On edit: pre-load saved selections by injecting Option elements via JS
using a data-preloaded=”[{id,text},…]” attribute on the select element
(build this JSON server-side by fetching product names / category names
for the saved apply_ids)
– When apply_to changes: destroy existing Select2, clear options, reinitialise
with the correct AJAX action for the new scope
FORM DEFAULTS for new rule: status=1, priority=10, discount_type=percentage,
apply_to=all, exclusive=0, bogo_get_discount=100
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
JAVASCRIPT — admin/js/admin.js
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
On DOM ready (jQuery):
1. DISCOUNT TYPE TOGGLE:
– Watch #discount_type change
– If value = ‘bogo’: hide #row_discount_value, show #row_bogo
– Otherwise: show #row_discount_value, hide #row_bogo
– Run on page load to set initial state
2. SCOPE TOGGLE + SELECT2 INIT:
Function handleScopeChange(scope, animate):
– If scope = ‘all’: hide #row_apply_ids (slideUp if animate, hide if not)
– Otherwise: show #row_apply_ids (slideDown if animate, show if not)
– Call initSelect2(scope)
Function initSelect2(scope):
– If #apply_ids already has Select2: destroy it and empty() the select
– If scope = ‘all’: return early
– Determine AJAX action: scope=’products’ → ‘wcdr_search_products’,
scope=’categories’ → ‘wcdr_search_categories’
– Init Select2 with:
ajax.url: wcdr.ajax_url
ajax.data: { action, nonce: wcdr.nonce, q: params.term || ” }
ajax.processResults: return { results: data }
minimumInputLength: 0
placeholder: ‘Type to search products…’ or ‘Type to search categories…’
allowClear: true, width: ‘100%’
– After init, read data-preloaded attribute, loop items,
append Option(text, id, true, true) for each, trigger(‘change’)
On page load: call handleScopeChange($(‘#apply_to’).val(), false)
On #apply_to change: call handleScopeChange($(this).val(), true)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CSS — admin/css/admin.css
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Frontend (cart/checkout):
.wcdr-discount-line { color: #2e7d32; font-weight: 600; }
Admin general:
– .wcdr-wrap h1 .dashicons: color #7f54b3, font-size 26px
– .wcdr-version: small grey version label
– .wcdr-table: vertically centered cells
– .wcdr-badge.exclusive: orange background, white text
– .wcdr-toggle.active: green tinted button
– .wcdr-toggle.inactive: red tinted button
– .wcdr-empty: centered, padded empty state cell
Form:
– .wcdr-section: white card, 1px border, border-radius 6px, box-shadow
– .wcdr-section h3: bottom border separator
– .wcdr-optional: small grey helper text
– .wcdr-submit-row with .button-hero: large prominent save button
– .required: red asterisk color
Select2:
– Selected tags: background #7f54b3 (WooCommerce purple), white text
– Highlighted option: background #7f54b3
– Border-color matching WP admin inputs
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
KNOWN BUGS TO AVOID — these were discovered and fixed during development.
Do NOT reproduce these mistakes:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
BUG 1 — Discount not applying (cart total always 0)
WRONG: hook into woocommerce_before_calculate_totals and call get_subtotal()
RIGHT: hook into woocommerce_cart_calculate_fees — get_subtotal() is
accurate at this point because WC has already summed item totals.
BUG 2 — Discount compounds on every page reload
WRONG: $product->set_price($new_price) inside any cart hook
RIGHT: $cart->add_fee($label, -$amount, false) — negative fee is
idempotent and never mutates stored product data.
BUG 3 — Fixed amount fee is silently dropped
WRONG: $label = $rule->rule_name . ‘ (‘ . wc_price($amount) . ‘ off)’;
RIGHT: $symbol = html_entity_decode(get_woocommerce_currency_symbol());
$label = $rule->rule_name . ‘ (‘ . $symbol . number_format($amount,2) . ‘ off)’;
BUG 4 — Scope check missing for fixed_amount rules
WRONG: only call product_matches_scope() inside per-type calculation helpers
RIGHT: check scope in the main rule-matching loop for ALL discount types
before adding any rule to $applied_rules
BUG 5 — Select Items field blank when changing scope
WRONG: render <option> elements server-side and show/hide the row via JS
RIGHT: use Select2 with AJAX (wp_ajax_ handlers) — reinitialise Select2
with the correct AJAX action each time scope changes
BUG 6 — Critical error from wp_roles()
WRONG: call wp_roles() directly in the admin form render method
RIGHT: remove user roles field entirely OR call it only inside an
admin_init or later hook where WordPress has fully initialised
BUG 7 — WooCommerce compatibility warning on activation
WRONG: no compatibility declaration
RIGHT: use before_woocommerce_init hook to call
FeaturesUtil::declare_compatibility() for both
‘custom_order_tables’ and ‘cart_checkout_blocks’
BUG 8 — Edit form has no visible Save button
WRONG: submit button inside a nested container with overflow or display issues
RIGHT: place the submit button in its own .wcdr-submit-row div outside
all .wcdr-section cards, directly before closing </form>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
FINAL OUTPUT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
– Create all files listed above with complete, working code
– Package everything into a ZIP file named wc-discount-rules.zip
– The ZIP should extract to a single folder: wc-discount-rules/
– The plugin must be installable directly via WordPress Admin →
Plugins → Add New → Upload Plugin with no additional setup required
– After activation, WooCommerce → Discount Rules menu must appear
with a working rules list, add form, edit form, and toggle controls
What Is Claude AI and Why Use It for WooCommerce Plugin Development?
Claude AI is an advanced AI assistant developed by Anthropic. It is specifically excellent at writing clean, well-structured PHP code for WordPress and WooCommerce, making it one of the best free tools available for WordPress plugin development without deep coding knowledge.
Why Claude AI Outperforms Other AI Tools for Plugin Development
- Generates complete, multi-file plugin structures in a single conversation
- Understands WooCommerce-specific hooks and API patterns
- Debugs and fixes its own code when you report issues
- Produces code that follows WordPress coding standards
- Handles complex requirements like database management, AJAX endpoints, and admin UI creation
You do not need a Claude Pro subscription to build this plugin. The free tier at claude.ai is sufficient to generate the complete plugin code. Simply describe what you want in plain English, and Claude will write all the PHP, CSS, and JavaScript files for you.
Features of Our Custom WooCommerce Discount Rules Plugin
Here is a complete breakdown of every feature included in the plugin we built using Claude AI:
Feature | Discount Type | Example |
Percentage Discount | Percentage | 20% off when cart total is $200 or more |
Fixed Amount Discount | Fixed Amount | $20 off on any purchase above $200 |
Fixed Price Rule | Fixed Price | Set Product A to always cost $15 |
Buy X Get Y (BOGO) | BOGO | Buy 2 Get 1 free on selected products |
Cart Total Conditions | All Types | Min $100, Max $500 cart value trigger |
Quantity Conditions | All Types | Discount activates when qty >= 5 |
Product-Specific Rules | All Types | Apply only to Product A or Product B |
Category Rules | All Types | Apply to entire “Electronics” category |
Scheduled Rules | All Types | Active from Jan 1 to Jan 31 only |
Priority System | All Types | Rule #1 always applies before Rule #2 |
Exclusive Rules | All Types | Only one discount applies at a time |
Unlimited Rules | All Types | Create as many rules as needed |
Admin Interface
The plugin adds a dedicated Discount Rules menu under WooCommerce in your WordPress admin. From here you can:
- View all rules in a clean sortable table
- Add new rules with an intuitive form
- Edit existing rules without losing your settings
- Toggle rules active or inactive with a single click
- Delete rules you no longer need
Cart and Checkout Display
When a discount rule triggers, customers see a clear discount line item on both the cart page and checkout page. The discount is shown in green with the rule name and exact savings amount — for example: “Summer Sale (20% off) — -$40.00”. Product prices themselves are never altered, keeping your store data clean and reliable.
How the Plugin Works — Technical Overview
The Negative Fee Approach
Our plugin uses WooCommerce’s built-in cart fee system to apply discounts. Instead of changing product prices (which causes compounding issues on every cart refresh), the plugin calculates the discount amount and adds it as a negative fee using $cart->add_fee(). This is WooCommerce’s recommended approach for programmatic discounts and is completely stable across all store configurations.
The Rule Evaluation Engine
When a customer visits the cart or checkout page, the plugin’s discount engine runs through the following process:
- Loads all active rules from the database, ordered by priority
- Reads the current cart subtotal from WooCommerce (after all items are calculated)
- Checks each rule’s conditions: date range, cart total min/max, quantity min/max, and product/category scope
- For rules that pass all conditions, calculates the discount amount based on the discount type
- Adds a single negative fee to the cart with a plain-text label showing the rule name and savings
- Caps the total discount at the cart subtotal so it never goes negative
Database Structure
The plugin creates a custom database table (wcdr_rules) during activation using WordPress’s dbDelta() function. Each rule is stored as a row with fields for all conditions, discount type, scope, scheduling, and priority. This makes rules persistent, editable, and fully manageable through the admin interface.
Step-by-Step: How to Create the WooCommerce Discount Rules Plugin Using Claude AI
Here are the exact steps we followed to build this plugin in our tutorial. You can replicate this entire process yourself on a free Claude AI account.
Step 1 — Open Claude AI and Start a New Conversation
Go to claude.ai and sign in or create a free account. Start a fresh conversation. It helps to set the context clearly before asking Claude to write code.
Step 2 — Describe the Plugin Features You Want
In plain English, tell Claude AI what you want to build. Be specific about the discount types, conditions, and admin interface requirements. For example:
“Create a WooCommerce discount rules plugin that supports percentage discounts, fixed amount discounts, and BOGO deals. It should have a clean admin interface under WooCommerce, allow conditions like minimum cart total, minimum quantity, product scope, and category scope, and display the discount on the cart and checkout pages.”
Step 3 — Claude AI Generates All Plugin Files
Claude will generate a complete, multi-file plugin structure including the main PHP file, a database class, a discount engine class, an admin UI class, CSS stylesheets, and JavaScript files. The output is production-ready code with proper WordPress hooks and WooCommerce API usage.
Step 4 — Ask Claude to Package It as a ZIP
Tell Claude: “Package all these files into a downloadable ZIP file.” Claude will use its computer tools to create the plugin directory, write all files, and compress them into a ZIP ready for WordPress installation.
Step 5 — Install the Plugin in WordPress
Download the ZIP file Claude generated. In your WordPress admin, go to Plugins → Add New → Upload Plugin. Upload the ZIP file and click Activate Plugin. The plugin is now live on your site.
Step 6 — Test and Report Any Issues Back to Claude
Test the plugin on your store. If anything does not work correctly, simply describe the issue to Claude in the same conversation. Claude will identify the bug, explain what caused it, fix the code, and produce an updated ZIP file. You repeat this process until the plugin works exactly as expected.
Installing the Plugin in WordPress — Complete Walkthrough
Prerequisites
- WordPress 5.0 or higher
- WooCommerce 5.0 or higher installed and active
- Admin access to your WordPress dashboard
Installation Steps
- Log into your WordPress admin dashboard
- Go to Plugins → Add New from the left sidebar
- Click the Upload Plugin button at the top of the page
- Click Choose File and select the wc-discount-rules.zip file you downloaded from Claude
- Click Install Now and wait for the upload to complete
- Click Activate Plugin once installation is successful
- Navigate to WooCommerce → Discount Rules to access the plugin
After activation, the plugin automatically creates the required database table and declares compatibility with WooCommerce HPOS (High-Performance Order Storage) and block-based Cart and Checkout. You will not see any compatibility warnings.
How to Create Your First Discount Rule
Creating a Percentage Discount Rule
This example creates a rule that gives customers 20% off when their cart total reaches $200.
- Go to WooCommerce → Discount Rules in your WordPress admin
- Click Add New Rule at the top of the page
- Enter a Rule Name, e.g. “20% Off Over $200”
- Set Status to Active
- Set Priority to 10 (lower number = higher priority)
- Under Discount Settings, select Percentage (%) off
- Enter 20 as the Discount Value
- Under Applies To, leave it set to All Products
- Under Conditions, enter 200 in the Min Cart field — leave Max Cart blank
- Leave the date fields empty for an ongoing rule
- Click Save Rule
Testing the Rule
Add products to your cart worth $250. Navigate to the cart page. You should see:
- Subtotal: $250.00
- 20% Off Over $200 (20% off): -$50.00
- Total: $200.00
Creating a Fixed Amount Discount Rule
To create a $20 off discount for orders above $200, follow the same steps but select Fixed Amount ($) off as the Discount Type and enter 20 as the Discount Value.
Creating a BOGO Rule
Select Buy X Get Y (BOGO) as the Discount Type. Set Buy quantity to 2, Get quantity to 1, and set the get discount to 100 for a completely free item. The plugin will automatically calculate the average price reduction across all items in the cart.
Common Issues and How to Fix Them Using Claude AI
During our development process, we encountered and fixed several bugs. Here is how we handled each one — and what you should watch for if you build your own version.
Discount not applying | Cart subtotal was being read before WooCommerce calculated it. Fixed by switching from woocommerce_before_calculate_totals hook to woocommerce_cart_calculate_fees hook where get_subtotal() returns the correct value. |
Discount compounding on refresh | set_price() was used on product objects, permanently mutating the price in the session. Fixed by switching to the negative fee approach using $cart->add_fee(). |
Fixed amount fee silently dropped | wc_price() was used in the fee label, which outputs HTML. WooCommerce strips HTML from fee names, corrupting the label. Fixed by using plain-text currency symbol instead. |
Select Items field blank | Product/category options were rendered server-side and could not update when the scope changed. Fixed by implementing Select2 with AJAX search endpoints. |
Critical error on form load | wp_roles() was called during form rendering before WordPress fully initialized. Fixed by removing the user roles field. |
No Save button on edit form | Submit button was nested inside a container with layout issues. Fixed by placing it in its own section outside all card containers. |
WooCommerce compatibility notice | Plugin did not declare HPOS or block checkout compatibility. Fixed by adding FeaturesUtil::declare_compatibility() calls in the before_woocommerce_init hook. |
In every case, the fix was simple: describe the problem to Claude AI in the same conversation, and Claude identified the root cause, explained the fix, and produced an updated version of the plugin. The debugging process for each bug took less than two minutes.
Tips for Getting the Best Results from Claude AI When Building Plugins
Be Specific in Your Initial Prompt
The more detail you provide upfront, the less back-and-forth you will need. Describe every feature, condition, and UI element you want in your first message. Vague prompts like “make a discount plugin” produce generic results. Specific prompts like “apply discounts as a negative cart fee using woocommerce_cart_calculate_fees hook” produce production-ready code.
Stay in the Same Conversation for Bug Fixes
Do not start a new conversation when you find a bug. Claude has the full context of what it built in the current conversation, which makes debugging far more accurate. Describe exactly what you did, what you expected, and what actually happened.
Test Each Version Thoroughly Before Moving On
After each fix, test all discount types and all conditions before reporting further issues. This prevents overlapping bug reports and keeps the conversation focused.
Ask Claude to Explain Its Fixes
Always ask Claude to explain why a bug happened and how the fix resolves it. This builds your understanding of WooCommerce internals and makes you a better store owner and developer.
Use Version Numbers
Ask Claude to increment the plugin version number with each update (1.0, 1.1, 1.2 etc.). This makes it easy to track which version is installed on your site and compare changes.
Frequently Asked Questions
Do I need coding experience to build a WooCommerce discount rules plugin with Claude AI?
No. Claude AI generates all the PHP, JavaScript, and CSS code for you. You only need to describe what you want in plain English, copy the generated files, and upload the ZIP to WordPress. Basic familiarity with the WordPress admin dashboard is sufficient.
Is the plugin safe to use on a live WooCommerce store?
Yes, provided you test it thoroughly on a staging site first. The plugin uses standard WordPress and WooCommerce APIs, follows WordPress coding standards, and applies discounts through WooCommerce’s built-in cart fee system. Always test on a staging environment before deploying to production.
Can I create unlimited discount rules with this plugin?
Yes. The plugin stores rules in a custom database table with no limit on the number of rules. You can create as many percentage, fixed amount, fixed price, and BOGO rules as your store requires.
Does the plugin work with WooCommerce HPOS (High-Performance Order Storage)?
Yes. The plugin explicitly declares compatibility with WooCommerce HPOS and block-based Cart and Checkout using the FeaturesUtil::declare_compatibility() method. You will not see any compatibility warnings in your WooCommerce admin.
Can I apply discounts to specific products or categories only?
Yes. Each rule has an “Applies To” setting with three options: All Products, Specific Products, and Specific Categories. When you select specific products or categories, a searchable Select2 dropdown appears where you can search and select exactly which products or categories should be discounted.
What happens if multiple discount rules apply to the same cart?
By default, all matching rules stack and their discounts are combined. If you want only the highest-priority rule to apply, mark it as “Exclusive.” An exclusive rule stops all other rules from applying once it matches the cart.
Can I schedule discount rules for specific dates like Black Friday?
Yes. Each rule has optional Start Date and End Date fields. The discount will only apply within the specified date range. Leave both fields blank for an ongoing rule with no expiry.
Is the discount shown to customers on the cart and checkout pages?
Yes. The discount appears as a clearly labeled line item in the cart and checkout totals, displayed in green. The label shows the rule name and the exact discount amount, for example: “Black Friday Deal (20% off): -$50.00”. Customers can see exactly how much they are saving before they complete their purchase.
Conclusion
Building a custom WooCommerce discount rules plugin using Claude AI is one of the most practical ways to add advanced pricing functionality to your store without paying for expensive premium plugins. In this guide, you saw exactly how to describe the plugin to Claude AI, how the generated code works, how to install and configure it, and how to fix any bugs that appear — all using the same AI conversation.
The complete plugin we built supports percentage discounts, fixed amount discounts, fixed price rules, and BOGO deals, with conditions for cart total, quantity, product scope, and category scope. It displays savings clearly on the cart and checkout pages, and is fully compatible with the latest WooCommerce features including HPOS.
If you want to skip the build process entirely, you can use the master prompt provided in this guide and paste it directly into Claude AI — it will generate the complete, bug-free plugin in a single session.
Try it today and stop paying for features you can build yourself. Subscribe to the Quick Tips YouTube channel for more tutorials on building WooCommerce tools with Claude AI.











