Added complete inventory tracking system for composable products: - Stock validation during product selection and add-to-cart - Automatic stock deduction on order completion/processing - Automatic stock restoration on order cancellation/refund - Stock status indicators with visual feedback (In stock, Low stock, Out of stock) - Prevention of out-of-stock item selection - Low stock warnings when 5 or fewer items remain - Order notes documenting all stock changes New files: - includes/Stock_Manager.php: Core stock management logic Modified files: - includes/Cart_Handler.php: Integrated stock validation - includes/Product_Selector.php: Added stock info to product data - includes/Plugin.php: Added Stock_Manager to includes - templates/product-selector.twig: Stock status display - assets/css/frontend.css: Stock indicator styling - languages/*.pot/*.po: 8 new translatable strings Version bumped to 1.1.0 with updated CHANGELOG. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
10 KiB
WooCommerce Composable Products - Implementation Summary
Overview
This document provides a technical overview of the WooCommerce Composable Products plugin implementation.
Version: 1.0.0 Created: 2024-12-31 AI-Generated: 100% created with Claude.AI assistance
Architecture
Plugin Structure
wc-composable-product/
├── assets/ # Frontend assets
│ ├── css/
│ │ ├── admin.css # Admin styles
│ │ └── frontend.css # Frontend styles
│ └── js/
│ ├── admin.js # Admin JavaScript
│ └── frontend.js # Frontend JavaScript
├── cache/ # Twig template cache
├── includes/ # PHP classes
│ ├── Admin/
│ │ ├── Product_Data.php # Product data tab
│ │ └── Settings.php # Settings page
│ ├── Cart_Handler.php # Cart integration
│ ├── Plugin.php # Main plugin class
│ ├── Product_Selector.php # Frontend selector
│ └── Product_Type.php # Custom product type
├── languages/ # Translation files
│ └── wc-composable-product.pot
├── templates/ # Twig templates
│ └── product-selector.twig
└── wc-composable-product.php # Main plugin file
Core Components
1. Main Plugin Class (Plugin.php)
Responsibilities:
- Singleton pattern implementation
- Twig template engine initialization
- Hook registration
- Component initialization
- Asset enqueuing
Key Methods:
instance(): Get singleton instanceinit_twig(): Initialize Twig with WordPress functionsrender_template(): Render Twig templatesadd_product_type(): Register composable product type
2. Product Type (Product_Type.php)
Extends: WC_Product
Key Features:
- Custom product type:
composable - Selection limit management (per-product or global)
- Pricing mode (fixed or sum)
- Product selection criteria (category/tag/SKU)
- Dynamic product availability
- Price calculation
Key Methods:
get_selection_limit(): Get max selectable itemsget_pricing_mode(): Get pricing calculation modeget_available_products(): Query available productscalculate_composed_price(): Calculate final price
3. Admin Settings (Admin/Settings.php)
Extends: WC_Settings_Page
Global Settings:
- Default selection limit
- Default pricing mode
- Display options (images, prices, total)
Integration: Adds tab to WooCommerce Settings
4. Product Data Tab (Admin/Product_Data.php)
Responsibilities:
- Add "Composable Options" tab to product edit page
- Render selection criteria fields
- Save product meta data
- Dynamic field visibility based on criteria type
Saved Meta:
_composable_selection_limit: Item limit_composable_pricing_mode: Pricing calculation_composable_criteria_type: Selection method_composable_categories: Selected categories_composable_tags: Selected tags_composable_skus: SKU list
5. Product Selector (Product_Selector.php)
Responsibilities:
- Render frontend product selection interface
- Prepare data for Twig template
- Apply display settings
Template Variables:
products: Available products arrayselection_limit: Max selectionspricing_mode: Pricing calculationshow_images/prices/total: Display flags
6. Cart Handler (Cart_Handler.php)
Responsibilities:
- Validate product selection
- Add selected products to cart data
- Calculate dynamic pricing
- Display selected products in cart
Hooks:
woocommerce_add_to_cart_validation: Validate selectionswoocommerce_add_cart_item_data: Store selectionswoocommerce_before_calculate_totals: Update priceswoocommerce_get_item_data: Display in cart
Frontend Implementation
Product Selector Template (product-selector.twig)
Features:
- Responsive grid layout
- Checkbox-based selection
- Product images and prices
- Real-time total calculation
- AJAX add-to-cart
Data Attributes:
data-product-id: Composable product IDdata-selection-limit: Max selectionsdata-pricing-mode: Pricing modedata-price: Individual product prices
JavaScript (frontend.js)
Functionality:
- Selection limit enforcement
- Visual feedback on selection
- Real-time price updates (sum mode)
- AJAX cart operations
- Error/success messages
Key Functions:
handleCheckboxChange(): Selection logicupdateTotalPrice(): Calculate totaladdToCart(): AJAX add-to-cartshowMessage(): User feedback
CSS Styling
Approach:
- Grid-based layout (responsive)
- Card-style product items
- Visual selection states
- Mobile-first design
- Breakpoints: 768px, 480px
Data Flow
Creating a Composable Product
- Admin selects "Composable product" type
- Configure selection limit and pricing mode
- Choose selection criteria (category/tag/SKU)
- Save product metadata
- WooCommerce registers product with custom type
Frontend Display
- Customer visits product page
Cart_HandlerrendersProduct_SelectorProduct_Type::get_available_products()queries products- Twig template renders grid with products
- JavaScript handles interactions
Adding to Cart
- Customer selects products (JavaScript validation)
- Click "Add to Cart" button
- AJAX request with selected product IDs
Cart_Handler::validate_add_to_cart()validatesCart_Handler::add_cart_item_data()stores selectionsCart_Handler::calculate_cart_item_price()updates price- Product added to cart with custom data
Cart Display
- WooCommerce loads cart
Cart_Handler::get_cart_item_from_session()restores dataCart_Handler::display_cart_item_data()shows selections- Price calculated dynamically on each cart load
Security Implementation
Input Sanitization
- Integers:
absint()for IDs and limits - Text:
sanitize_text_field()for modes and types - Textarea:
sanitize_textarea_field()for SKUs - Arrays:
array_map()with sanitization functions
Output Escaping
- HTML:
esc_html(),esc_html_e() - Attributes:
esc_attr() - URLs:
esc_url() - JavaScript: Localized scripts with escaped data
Validation
- Selection limit enforcement
- Product availability verification
- Cart data validation
- Nonce verification (via WooCommerce)
Internationalization
Text Domain
wc-composable-product
Translation Functions
__(): Return translated string_e(): Echo translated stringsprintf()with__(): Variable substitution
POT File
Generated template: languages/wc-composable-product.pot
Supported Locales (per CLAUDE.md):
- en_US (English)
- de_DE, de_DE_informal (German - Germany)
- de_CH, de_CH_informal (German - Switzerland)
- fr_CH (French - Switzerland)
- it_CH (Italian - Switzerland)
Performance Considerations
Caching
- Twig templates cached in
cache/directory - Auto-reload enabled in debug mode
- Optimized Composer autoloader
Database Queries
- Efficient
WP_Queryfor product selection - Meta queries for SKU filtering
- Taxonomy queries for category/tag filtering
Asset Loading
- Scripts only on relevant pages
- Minification ready (use build tools)
- Conditional enqueuing
Extensibility
Hooks & Filters
Available Filters:
wc_composable_settings: Modify settings arraywoocommerce_product_class: Custom product classproduct_type_selector: Product type registration
Customization Points:
- Twig templates (override in theme)
- CSS styling (enqueue custom styles)
- JavaScript behavior (extend object)
Developer API
// Get composable product
$product = wc_get_product($product_id);
// Check if composable
if ($product->get_type() === 'composable') {
// Get available products
$products = $product->get_available_products();
// Get selection limit
$limit = $product->get_selection_limit();
// Calculate price
$price = $product->calculate_composed_price($selected_ids);
}
Testing Checklist
Admin Testing
- Product type appears in dropdown
- Composable Options tab displays
- Selection criteria toggle works
- Meta data saves correctly
- Settings page accessible
- Global defaults apply
Frontend Testing
- Product selector renders
- Selection limit enforced
- Price calculation accurate (both modes)
- AJAX add-to-cart works
- Cart displays selections
- Checkout processes correctly
Edge Cases
- Empty criteria (no products)
- Out of stock products excluded
- Invalid product selections rejected
- Multiple cart items unique
- Session persistence
Known Limitations
- Variable Products: Currently supports simple products in selection
- Grouped Products: Cannot be used as selectable items
- Stock Management: No automatic stock reduction for selected items
- Caching: Template cache needs manual clearing after updates
Future Enhancements
Potential features for future versions:
- Variable product support in selection
- Quantity selection per item (not just presence)
- Visual bundle previews
- Advanced pricing rules
- Stock management integration
- Product recommendations
- Selection templates/presets
- Multi-currency support enhancements
Dependencies
Runtime
- PHP 8.3+
- WordPress 6.0+
- WooCommerce 8.0+
- Twig 3.0 (via Composer)
Development
- Composer for dependency management
- WP-CLI for i18n operations (optional)
Deployment
Production Checklist
- Run
composer install --no-dev --optimize-autoloader - Ensure
vendor/directory is included - Ensure
cache/directory is writable - Test on staging environment
- Clear all caches after activation
- Verify WooCommerce compatibility
Release Package
Must include:
- All PHP files
vendor/directory- Assets (CSS, JS)
- Templates
- Language files
- Documentation
Must exclude:
.git/directorycomposer.lock- Development files
wp-core/,wp-plugins/symlinks
Support & Maintenance
Code Standards
- WordPress Coding Standards
- WooCommerce best practices
- PSR-4 autoloading
- Inline documentation
Version Control
- Semantic versioning (MAJOR.MINOR.PATCH)
- Changelog maintained
- Annotated git tags
- Development on
devbranch
Last Updated: 2024-12-31 Maintainer: Marco Graetsch AI Assistant: Claude.AI (Anthropic)