Files
wc-composable-product/IMPLEMENTATION.md
magdev 1edb0be3d9 Initial implementation of WooCommerce Composable Products plugin
Implemented custom WooCommerce product type allowing customers to build their own
product bundles by selecting from predefined sets of products.

Features:
- Custom "Composable Product" type with admin interface
- Product selection by category, tag, or SKU
- Configurable selection limits (global and per-product)
- Dual pricing modes: fixed price or sum of selected products
- Modern responsive frontend with Twig templates
- AJAX add-to-cart functionality
- Full internationalization support (.pot file)
- WooCommerce settings integration
- Comprehensive documentation

Technical implementation:
- PHP 8.3+ with PSR-4 autoloading
- Twig 3.0 templating engine via Composer
- Vanilla JavaScript with jQuery for frontend interactions
- WordPress and WooCommerce hooks for seamless integration
- Security: input sanitization, validation, and output escaping
- Translation-ready with text domain 'wc-composable-product'

Documentation:
- README.md: Project overview and features
- INSTALL.md: Installation and usage guide
- IMPLEMENTATION.md: Technical architecture
- CHANGELOG.md: Version history

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-31 00:38:29 +01:00

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 instance
  • init_twig(): Initialize Twig with WordPress functions
  • render_template(): Render Twig templates
  • add_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 items
  • get_pricing_mode(): Get pricing calculation mode
  • get_available_products(): Query available products
  • calculate_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 array
  • selection_limit: Max selections
  • pricing_mode: Pricing calculation
  • show_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 selections
  • woocommerce_add_cart_item_data: Store selections
  • woocommerce_before_calculate_totals: Update prices
  • woocommerce_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 ID
  • data-selection-limit: Max selections
  • data-pricing-mode: Pricing mode
  • data-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 logic
  • updateTotalPrice(): Calculate total
  • addToCart(): AJAX add-to-cart
  • showMessage(): 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

  1. Admin selects "Composable product" type
  2. Configure selection limit and pricing mode
  3. Choose selection criteria (category/tag/SKU)
  4. Save product metadata
  5. WooCommerce registers product with custom type

Frontend Display

  1. Customer visits product page
  2. Cart_Handler renders Product_Selector
  3. Product_Type::get_available_products() queries products
  4. Twig template renders grid with products
  5. JavaScript handles interactions

Adding to Cart

  1. Customer selects products (JavaScript validation)
  2. Click "Add to Cart" button
  3. AJAX request with selected product IDs
  4. Cart_Handler::validate_add_to_cart() validates
  5. Cart_Handler::add_cart_item_data() stores selections
  6. Cart_Handler::calculate_cart_item_price() updates price
  7. Product added to cart with custom data

Cart Display

  1. WooCommerce loads cart
  2. Cart_Handler::get_cart_item_from_session() restores data
  3. Cart_Handler::display_cart_item_data() shows selections
  4. 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 string
  • sprintf() 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_Query for 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 array
  • woocommerce_product_class: Custom product class
  • product_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

  1. Variable Products: Currently supports simple products in selection
  2. Grouped Products: Cannot be used as selectable items
  3. Stock Management: No automatic stock reduction for selected items
  4. 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

  1. Run composer install --no-dev --optimize-autoloader
  2. Ensure vendor/ directory is included
  3. Ensure cache/ directory is writable
  4. Test on staging environment
  5. Clear all caches after activation
  6. Verify WooCommerce compatibility

Release Package

Must include:

  • All PHP files
  • vendor/ directory
  • Assets (CSS, JS)
  • Templates
  • Language files
  • Documentation

Must exclude:

  • .git/ directory
  • composer.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 dev branch

Last Updated: 2024-12-31 Maintainer: Marco Graetsch AI Assistant: Claude.AI (Anthropic)