=== Mamba Cache for WooCommerce ===

Contributors: mamba
Tags: woocommerce, performance, caching, optimization, speed
Requires at least: 5.0
Tested up to: 6.9
WC requires at least: 10.0.0
WC tested up to: 10.4.3
Requires PHP: 7.4
Stable tag: 1.0.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

The ultimate WooCommerce performance plugin with intelligent caching, media optimization, database cleanup, and CDN integration.

== Description ==

Mamba is a comprehensive performance optimization plugin specifically designed for WooCommerce stores. It dramatically improves page load times, and overall user experience.

### ⚡ Page Caching

Full-page caching optimized for WooCommerce catalog pages, products, categories, and shop pages with automatic cache variants:

– **Product Pages** – Individual product pages with variant caching
– **Category/Tag Pages** – Product listing pages with pagination support
– **Shop Page** – Main store catalog page
– **Search Results** – WooCommerce product search pages
– **Desktop/Mobile Variants** – Separate caches for different devices
– **Language Variants** – WPML/Polylang support for multilingual stores
– **Currency Variants** – Multi-currency support (WooCommerce Multilingual, etc.)
– **Geolocation Variants** – Location-based caching for tax/geo-pricing
– **Tax Display Variants** – Tax-inclusive/exclusive display modes
– **Smart Exclusions** – Logged-in users, cart/checkout/account pages automatically excluded
– **Stale-While-Revalidate** – Serves stale content during regeneration
– **Tag-Based Invalidation** – Precise purging without full cache clears

### 🛒 Store API Caching (Premium)

High-performance caching for WooCommerce Store API endpoints used by blocks and headless setups:

– **Product Listings** – /wp-json/wc/store/v1/products endpoint caching
– **Cart Data** – /wp-json/wc/store/v1/cart endpoint caching
– **Product Categories** – Category and tag listing endpoints
– **Product Variations** – Variable product data caching
– **Scoped Vary Headers** – Per-customer cache variants based on session/currency
– **ETag/304 Support** – Efficient browser revalidation for API responses
– **Per-Cart Microcache** – Short-lived cache smooths traffic bursts during sales
– **Automatic Invalidation** – Clears on product edits, pricing changes, coupon updates, and cart mutations

### 🖼️ Media Optimization (Premium)

Comprehensive image optimization specifically for WooCommerce product images and media:

– **LCP Optimization** – Identifies and preloads Largest Contentful Paint images on product pages
– **Product Image Compression** – Lossy/lossless compression for product galleries
– **WebP/AVIF Conversion** – Automatic format conversion for product images
– **Bulk Processing** – Optimize existing product catalog in batches
– **CDN Integration** – Automatic purging of optimized images from CDN
– **WooCommerce Integration** – Works with product variations and gallery images

### 🗄️ Database Optimization

Automated cleanup of WooCommerce database bloat from orders, products, and sessions:

– **Order-Related Cleanup** – Expired order items, orphaned meta, system notes
– **Product Cleanup** – Orphaned product data, unused attributes, draft products
– **Session Management** – Expired customer sessions and cart data
– **Inventory Cleanup** – Reserved stock and availability data
– **18 Automated Tasks** – Comprehensive WooCommerce table optimization
– **Configurable Scheduling** – Run during low-traffic periods
– **Retention Policies** – Customizable cleanup retention for different data types

### 🚀 Overhead Optimization

Reduce WooCommerce bloat and improve catalog page load times:

– **Asset Optimization** *(Premium)* – Dequeue WooCommerce CSS/JS on non-product pages
– **Checkout Optimization** *(Premium)* – Optimize payment gateway loading and form performance
– **Price HTML Simplification** – Streamline product price display markup
– **Hover Prefetch** – Preload product/category pages on hover for instant navigation
– **Resource Hints** – DNS prefetch for payment gateways and external services
– **Heartbeat Control** – Reduce AJAX frequency on product edit screens

### 🌐 CDN Integration

Deep integration with major CDN providers for WooCommerce assets and pages:

– **Cloudflare** – Direct API integration with APO (Automatic Platform Optimization)
– **Bunny CDN** – Pull zone API with tag-based purging
– **Generic Webhook** – Custom purge endpoints for enterprise CDNs
– **URL Rewriting** – Rewrite product image and asset URLs to CDN
– **WooCommerce-Specific Purging** – Purge product/category pages on inventory changes

### 🎯 Smart Invalidation

Surgical cache purging optimized for WooCommerce workflows:

– **Product Updates** – Purges product page, related categories, and search results
– **Inventory Changes** – Stock level updates trigger targeted purges
– **Pricing Updates** – Currency/tax changes clear affected catalog pages
– **Category Management** – Product moves between categories update cache accordingly
– **Order Processing** – Stock reductions from orders invalidate affected pages
– **Coupon Changes** – Store-wide coupon updates clear cart/product caches

### 📊 Performance Monitoring

Real-time statistics and health monitoring for WooCommerce stores:

– **Catalog Performance** – Track product page and category page load times
– **Cache Coverage** – Monitor percentage of WooCommerce pages cached
– **Conversion Impact** – Track performance improvements on checkout flows
– **Database Metrics** – Monitor table sizes and cleanup effectiveness
– **Savings Reports** – Bandwidth and database savings from optimizations

### 🛠️ Developer-Friendly

Comprehensive hooks and APIs for WooCommerce customization:

– **60+ Filters** – Customize cache keys, TTL, invalidation for products/categories
– **30+ Actions** – Hook into product updates, order processing, cart changes
– **WP-CLI Commands** – Command-line cache management for WooCommerce sites
– **REST API** – Programmatic cache control for headless WooCommerce
– **Multisite Support** – Per-site caching in WooCommerce multisite networks

### 🔧 Compatibility

– **WooCommerce 5.0+** – Full compatibility with core WooCommerce features
– **WooCommerce Blocks** – Optimized for block-based product pages
– **HPOS** – High-Performance Order Storage compatible
– **Multilingual** – WPML, Polylang, WooCommerce Multilingual support
– **Multi-currency** – Compatible with currency switcher plugins
– **Page Builders** – Elementor and Breakdance integration
– **Object Cache** – Redis, Memcached support for high-traffic stores

== Command Line & API Access ==

Mamba provides comprehensive command-line and programmatic access for WooCommerce store automation and integration.

### WP-CLI Commands

Full command-line interface for WooCommerce cache management and automation:

**Cache Management:**

– `wp mamba purge` – Purge all cache (page cache, Store API, fragments)
– `wp mamba purge page` – Purge only page cache
– `wp mamba purge api` – Purge only Store API cache
– `wp mamba purge url <url>` – Purge specific WooCommerce product/category URL
– `wp mamba purge product <id>` – Purge cache for specific product ID
– `wp mamba purge category <slug>` – Purge cache for specific category

**Warmup Operations:**

– `wp mamba warmup` – Start background cache warmup for all catalog pages
– `wp mamba warmup products` – Warm up all product pages
– `wp mamba warmup categories` – Warm up all category/tag pages
– `wp mamba warmup shop` – Warm up main shop page
– `wp mamba warmup status` – Check warmup job progress

**Database Operations:**

– `wp mamba db optimize` – Run all database cleanup tasks
– `wp mamba db optimize sessions` – Clean expired WooCommerce sessions
– `wp mamba db optimize orders` – Clean orphaned order data
– `wp mamba db optimize products` – Clean orphaned product data
– `wp mamba db status` – Show database optimization status

**Monitoring & Diagnostics:**

– `wp mamba status` – Display comprehensive cache and performance statistics
– `wp mamba status detailed` – Show detailed metrics including hit rates, coverage, and savings
– `wp mamba config` – Display current Mamba configuration
– `wp mamba test` – Run cache functionality tests

**Examples:**

“`
# Purge all cache
wp mamba purge

# Warm up product catalog after bulk import
wp mamba warmup products

# Clean database after order migration
wp mamba db optimize orders

# Check cache performance
wp mamba status detailed
“`

### REST API Endpoints

Programmatic access to Mamba's WooCommerce caching and optimization features:

**Status & Monitoring:**

– `GET /wp-json/mamba/v1/status` – Cache status, hit rates, coverage metrics
– `GET /wp-json/mamba/v1/stats` – Detailed performance statistics
– `GET /wp-json/mamba/v1/warmup/{job_id}` – Background warmup job status
– `GET /wp-json/mamba/v1/db/counts` – Database cleanup task counts

**Cache Management:**

– `POST /wp-json/mamba/v1/purge` – Purge all caches
– `POST /wp-json/mamba/v1/purge/page` – Purge page cache only
– `POST /wp-json/mamba/v1/purge/api` – Purge Store API cache only
– `POST /wp-json/mamba/v1/purge/url` – Purge specific URL (body: `{url: "https://example.com/product/test"}`)
– `POST /wp-json/mamba/v1/purge/product/{id}` – Purge specific product
– `POST /wp-json/mamba/v1/purge/category/{slug}` – Purge specific category

**Warmup Operations:**

– `POST /wp-json/mamba/v1/warmup` – Start background warmup
– `POST /wp-json/mamba/v1/warmup/products` – Warm up product pages
– `POST /wp-json/mamba/v1/warmup/categories` – Warm up category pages
– `GET /wp-json/mamba/v1/warmup/jobs` – List active warmup jobs

**Database Operations:**

– `POST /wp-json/mamba/v1/db/optimize` – Run database cleanup
– `POST /wp-json/mamba/v1/db/optimize/{task}` – Run specific cleanup task
– `GET /wp-json/mamba/v1/db/tasks` – List available cleanup tasks
– `GET /wp-json/mamba/v1/db/overview` – Database optimization overview

**Configuration:**

– `GET /wp-json/mamba/v1/settings` – Get current settings
– `POST /wp-json/mamba/v1/settings` – Update settings (requires admin authentication)
– `GET /wp-json/mamba/v1/cdn/test` – Test CDN connection
– `POST /wp-json/mamba/v1/cdn/purge` – Send CDN purge request

**Authentication:**

All REST endpoints require WordPress admin authentication. Use standard WordPress authentication methods (cookies, application passwords, or OAuth).

**Examples:**

“`
# Get cache status
curl -X GET https://example.com/wp-json/mamba/v1/status \
  -u username:password

# Purge product cache
curl -X POST https://example.com/wp-json/mamba/v1/purge/product/123 \
  -u username:password

# Start warmup
curl -X POST https://example.com/wp-json/mamba/v1/warmup \
  -u username:password

# Get database counts
curl -X GET https://example.com/wp-json/mamba/v1/db/counts \
  -u username:password
“`

### Integration Examples

**Automated Product Updates:**

When updating products via API, automatically purge affected cache:

“`
# After updating product via WooCommerce REST API
curl -X POST https://example.com/wp-json/mamba/v1/purge/product/123 \
  -u username:password
“`

**Deployment Scripts:**

Include cache warmup in deployment pipelines:

“`
# After deployment, warm up critical pages
wp mamba warmup shop
wp mamba warmup categories
wp mamba purge  # Clear any stale cache
“`

**Monitoring Integration:**

Monitor WooCommerce performance in external systems:

“`
# Check cache hit rates
wp mamba status | grep "Hit Rate"
“`

### Minimum Requirements

– WordPress 5.0 or higher
– WooCommerce 5.0 or higher
– PHP 7.4 or higher
– MySQL 5.6 or higher or MariaDB 10.1 or higher

### Recommended Server Configuration

– PHP 8.0+ for optimal performance
– Redis or Memcached for object caching
– Apache or Nginx with mod_rewrite enabled
– At least 256MB PHP memory limit

== Frequently Asked Questions ==

= How does Mamba handle WooCommerce product pages? =

Mamba caches individual product pages with full variant support. Each product page is cached separately, and updates to product data (price, stock, description) automatically invalidate the cache. Variable products are handled intelligently, caching each variation combination.

= What happens when I update a product? =

When you update a WooCommerce product (price, stock, description, images), Mamba automatically:

– Purges the product's individual page cache
– Purges any category pages containing that product
– Clears related Store API caches
– Sends purge requests to connected CDNs
– Optionally triggers cache warmup for affected pages

= How does caching work with WooCommerce categories? =

Category and tag pages are cached with pagination support. When products are added/removed from categories, or when category settings change, Mamba purges affected category pages. This ensures category listings always show current product inventory.

= Does Mamba cache the shop page and search results? =

Yes! The main shop page, WooCommerce search results, and all product listing pages are cached. Search results are not cached by default to prevent serving personalized search data, but this can be customized with filters.

= How does Mamba handle WooCommerce sessions and cart data? =

Mamba intelligently excludes dynamic WooCommerce content from caching:

– Logged-in users never see cached pages
– Cart, checkout, and account pages are never cached
– Cart fragments are cached per-session for guests
– Session-based personalization (prices, availability) is respected

= What about variable products and product variations? =

Variable products are fully supported. Each variation combination can be cached separately based on your store's caching rules. Stock changes, price updates, and visibility changes for variations trigger appropriate cache invalidation.

= How does Mamba work with WooCommerce Multilingual? =

Mamba integrates with WPML, Polylang, and WooCommerce Multilingual plugins. Each language gets separate cache variants, ensuring multilingual stores serve correct content to each language audience.

= Can Mamba cache WooCommerce REST API responses? =

Yes, with the Premium version! Store API endpoints (used by WooCommerce Blocks) are cached with proper invalidation. This dramatically speeds up block-based product pages and headless WooCommerce implementations.

= How does Mamba handle inventory changes? =

Stock level changes trigger immediate cache purges for affected products. When orders reduce inventory, Mamba purges the product page and related category pages to ensure accurate stock display.

= What about pricing changes and currency switching? =

Mamba caches different price displays and currencies separately. When pricing rules change or currencies are updated, affected caches are purged. Currency switcher plugins are fully supported.

= How does Mamba optimize WooCommerce database performance? =

Mamba includes 18 automated database cleanup tasks specifically for WooCommerce:

– Expired customer sessions and cart data
– Orphaned order items and metadata
– Unused product attributes and terms
– System order notes and download logs
– Reserved stock cleanup
– HPOS migration cleanup

= Is Mamba compatible with my hosting provider? =

Mamba works with all standard WordPress hosting providers. It uses standard WordPress APIs and doesn't require special server configurations. For optimal performance, we recommend hosts that support Redis or Memcached.

= Does Mamba work with page builders? =

Yes! Mamba has built-in support for Elementor and Breakdance. It automatically detects content changes and purges affected cache entries.

= Can I use Mamba with a CDN? =

Absolutely. Mamba integrates with Cloudflare, Bunny CDN, and generic webhook endpoints. It can also rewrite asset URLs to use your CDN hostname.

= How does Mamba handle cache invalidation? =

Mamba uses intelligent, tag-based invalidation. Instead of clearing entire cache, it only purges affected pages. For example, when a product is updated, only that product's page and related category pages are purged.

= Is the cache persistent across deployments? =

Cache files are stored in `wp-content/cache/mamba/` and persist across deployments. Object cache (if available) also persists. We recommend excluding the cache directory from version control.

= Does Mamba work with WooCommerce HPOS? =

Yes, Mamba is fully compatible with WooCommerce High-Performance Order Storage (HPOS/COT).

= Can I customize cache behavior? =

Yes, extensively! Mamba provides 60+ filters for developers to customize TTL, cache keys, invalidation logic, and more. See our [Developer Reference](docs/api-reference.html) for details.

= What happens if I deactivate Mamba? =

All cache files are safely removed on deactivation. Your original site performance returns to normal. No data is lost, but cached content will need to be regenerated.

= Can I run Mamba on a multisite network? =

Yes! Mamba supports WordPress Multisite with per-site caching. Activate network-wide or per-site as needed.

= How do I monitor cache performance? =

Mamba provides real-time statistics on the **Dashboard** tab, including hit rates, generation times, coverage percentage, and total savings.

= Does Mamba affect SEO? =

No, Mamba improves SEO by making your site faster. Faster sites rank better in search engines. All cache variants are properly handled for SEO.

= Can I exclude certain pages from caching? =

Yes, use the `mamba_cache_bypass` filter or add `define('MAMBA_CACHE_BYPASS', true);` to specific pages.

= How do I clear the cache? =

Use the "Purge All Cache" button in the admin bar or Mamba dashboard. For specific URLs, use "Purge This Page" from the admin bar.

= What about security? =

Mamba follows WordPress security best practices. All admin actions use nonces, input is sanitized, and cache files are protected with .htaccess rules.

= Can I use Mamba with other caching plugins? =

We recommend using Mamba as your primary caching solution. Disable other caching plugins to avoid conflicts.

== Screenshots ==

== External Services ==

This plugin connects to external services in specific scenarios. Below is a complete list of all external service integrations:

= CDN Integration (Optional, User-Configured) =

When you configure CDN integration in the plugin settings, Mamba connects to your chosen CDN provider's API to purge cached content:

**Cloudflare**
* Service: Cloudflare CDN and APO (Automatic Platform Optimization)
* Data sent: Zone ID, purge requests (URLs or cache tags), API authentication token
* When: Only when you configure Cloudflare integration and trigger cache purges
* Terms of Service: https://www.cloudflare.com/terms/
* Privacy Policy: https://www.cloudflare.com/privacypolicy/

**Bunny CDN**
* Service: Bunny CDN pull zone management
* Data sent: Pull zone ID, purge requests (URLs or cache tags), API key
* When: Only when you configure Bunny CDN integration and trigger cache purges
* Terms of Service: https://bunny.net/tos/
* Privacy Policy: https://bunny.net/privacy/

**Fastly**
* Service: Fastly CDN cache management
* Data sent: Service ID, purge requests (URLs or surrogate keys), API token
* When: Only when you configure Fastly integration and trigger cache purges
* Terms of Service: https://www.fastly.com/terms/
* Privacy Policy: https://www.fastly.com/privacy/

**Generic Webhook**
* Service: Custom webhook endpoint (user-defined)
* Data sent: Purge payload as configured by user
* When: Only when you configure a custom webhook and trigger cache purges
* Note: You control the endpoint and data format

= DNS Prefetch and Preconnect Hints (Optional, User-Configured) =

When enabled, this plugin adds DNS prefetch and preconnect resource hints to help browsers establish early connections to domains your site already uses. **The plugin does not load any files from these domains** - it only adds HTML hints like `<link rel="dns-prefetch" href="...">` to improve performance for resources your site already loads.

Common domains that may be included in auto-detection (if enabled):
* Google Fonts (fonts.googleapis.com, fonts.gstatic.com) - for sites using Google Fonts
* Google Analytics (www.google-analytics.com) - for sites using Google Analytics
* Payment gateways (js.stripe.com, www.paypal.com, etc.) - for WooCommerce checkout pages

These hints only benefit domains your site already uses. No data is sent to these domains by the plugin itself.

= Freemius SDK (License Management) =

This plugin uses Freemius for license management and optional usage analytics:
* Service: Freemius SDK
* Data sent: License key validation, optional anonymous usage statistics (if opted in)
* When: License activation, plugin updates, optional analytics
* Terms of Service: https://freemius.com/terms/
* Privacy Policy: https://freemius.com/privacy/

== Developer Notes ==

= Inline Scripts =

This plugin uses `wp_enqueue_script()`, `wp_add_inline_script()`, and `wp_localize_script()` for the majority of JavaScript. Three inline scripts remain as legitimate exceptions where dynamic PHP data must be generated at runtime:

1. **Welcome Modal** (`src/Lifecycle/Welcome.php`) - Contains dynamic nonces and AJAX callbacks for the one-time activation modal. This script runs only once per installation.

2. **Toast Notifications** (`src/Modules/Caching/Controller.php`) - Displays cache purge/warmup notifications with dynamic messages passed from PHP. These are transient UI elements.

3. **Media Bulk Optimization** (`src/Modules/Media/views/TabMedia.php`) - Contains PHP-generated statistics, server capability checks (`wp_image_editor_supports()`), and batch processing state that cannot be predetermined.

All other scripts have been moved to external files with data passed via `wp_localize_script()`.

== Changelog ==

= 1.0.0 =
* Initial release

== Upgrade Notice ==

= 1.0.0 =
First stable release. If upgrading from beta versions, review settings as some option names may have changed.
