### Multisite Cache Operations Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Demonstrates how to perform cache operations on specific sites, multiple sites, or the entire network in a multisite installation. Also shows how to get stats for a specific site. ```bash # Run on specific site wp millicache clear --url=site1.example.com ``` ```bash # Clear specific sites wp millicache clear --site=1,2,3 ``` ```bash # Clear entire network wp millicache clear --network=1 ``` ```bash # Stats for specific site wp millicache stats --flag="2:*" ``` -------------------------------- ### Complete MilliCache Configuration Example Source: https://millipress.com/docs/millicache/02-configuration/02-reference A comprehensive example of wp-config.php settings for MilliCache, including storage, cache settings, and exclusions. ```php 'POST', 33 'callback' => function() { 34 millicache_clear_cache_by_flags( [ 'membership:*' ] ); 35 return [ 'success' => true ]; 36 }, 37 'permission_callback' => function() { 38 return current_user_can( 'manage_options' ); 39 }, 40 ] ); 41} ); ``` -------------------------------- ### Install Acorn MilliCache Companion Package Source: https://millipress.com/docs/millicache Use Composer to install the Acorn MilliCache companion package for integration with Roots stacks. ```bash composer require millipress/acorn-millicache ``` -------------------------------- ### Install MilliCache Drop-in Source: https://millipress.com/docs/millicache/09-troubleshooting/02-faq Use this WP-CLI command to install the MilliCache drop-in file after enabling WP_CACHE. This is a necessary step for the plugin to function. ```bash wp millicache drop ``` -------------------------------- ### Get Configuration Values Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Displays current configuration values, optionally filtered by a specific key. Use `--show-source` to see where each value originates. ```bash wp millicache config get [] [--show-source] [--format=] ``` ```bash # View all settings wp millicache config get ``` ```bash # View specific module wp millicache config get cache ``` ```bash # View specific setting wp millicache config get cache.ttl ``` ```bash # View setting as JSON wp millicache config get cache.ttl --format=json ``` ```bash # Show setting sources wp millicache config get --show-source ``` -------------------------------- ### Descriptive Rule ID Example Source: https://millipress.com/docs/millicache/04-rules/03-examples Illustrates the best practice of using descriptive rule IDs with a namespace and purpose, contrasting it with generic IDs. ```php Rules::create( 'mysite:woo-cart-bypass', 'php' ) ``` ```php Rules::create( 'rule1', 'php' ) ``` -------------------------------- ### Lazy Loading Example in PHP Source: https://millipress.com/docs/millicache/07-developers/01-architecture Demonstrates lazy loading where the storage subsystem is not connected until the first cache operation is performed. This optimizes resource usage by initializing components only when needed. ```php // Storage isn't connected until the first cache operation $engine->storage()->get_cache( $key ); ``` -------------------------------- ### Configuration Management with Settings Source: https://millipress.com/docs/millicache/07-developers/01-architecture Shows how to access and modify plugin settings using the Settings class, which acts as a facade for MilliBase configuration. Supports getting, setting, importing, and exporting settings. ```php 1use MilliCacheCoreSettings; 2 3$settings = Settings::instance(); 4 5// Get settings 6$ttl = $settings->get( 'cache.ttl' ); 7$cache = $settings->get( 'cache' ); 8 9// Set settings 10$settings->set( 'cache.ttl', 3600 ); 11 12// Import/Export 13$settings->export( 'cache' ); 14$settings->import( $data ); ``` -------------------------------- ### Install MilliCache via Composer Source: https://millipress.com/docs/millicache/01-getting-started/20-installation Use this command to install MilliCache and its dependencies when managing WordPress with Composer. ```bash composer require millipress/millicache ``` -------------------------------- ### MilliCache Status Header Example Source: https://millipress.com/docs/millicache/05-usage/10-how-caching-works Example of the debug header used to view the cache status of a request. This helps in diagnosing caching behavior. ```http X-MilliCache-Status: hit ``` -------------------------------- ### wp millicache config get Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Display current configuration values, optionally filtered by key and showing the source of each value. ```APIDOC ## wp millicache config get ### Description Display current configuration values. ### Method `wp millicache config get` ### Parameters #### Arguments - `` (string) - Module or setting key (e.g., `cache` or `cache.ttl`) #### Options - `--show-source` (boolean) - Show where each value comes from - `--format=` (string) - Output: `table`, `json`, `yaml`, `csv` (default: `table`) ### Examples ```bash # View all settings wp millicache config get # View specific module wp millicache config get cache # View specific setting wp millicache config get cache.ttl # View setting as JSON wp millicache config get cache.ttl --format=json # Show setting sources wp millicache config get --show-source ``` ### Source Values - `constant` — Defined in wp-config.php - `file` — Set in config file - `database` — Saved via admin or CLI - `default` — Built-in default value ``` -------------------------------- ### Open Interactive Redis CLI Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Launches an interactive Redis CLI session using the configured connection settings. Requires `redis-cli` to be installed on the system. Provides common Redis commands for reference. ```bash wp millicache cli ``` ```redis PING # Check connection KEYS mll:* # List MilliCache keys DBSIZE # Get key count INFO memory # Check memory usage QUIT # Exit CLI ``` -------------------------------- ### Clear Cache with Site Prefix (WP-CLI) Source: https://millipress.com/docs/millicache/03-cache-flags/03-custom-flags On multisite installations, use WP-CLI with a site prefix to target specific sites. ```bash # Multisite: Include site prefix wp millicache clear --flag="2:post:*" wp millicache clear --flag="*:home" ``` -------------------------------- ### Initialize Request Processor in PHP Source: https://millipress.com/docs/millicache/07-developers/01-architecture Instantiate the Request Processor to handle incoming requests. This is used to get cache keys and determine if a request is cacheable. ```php $request = new MilliCacheEngineRequestProcessor( $config ); // Get cache key $hash = $request->get_hash(); // Check if cacheable $cacheable = $request->is_cacheable(); ``` -------------------------------- ### Install Acorn MilliCache Companion Package Source: https://millipress.com/docs/millicache/01-getting-started/10-introduction Use Composer to install the Acorn MilliCache companion package for integration with Roots stacks using Acorn. This package adds Laravel middleware for automatic caching of Acorn route responses. ```bash 1composer require millipress/acorn-millicache ``` -------------------------------- ### Testing MilliCache Connection with WP-CLI Source: https://millipress.com/docs/millicache/08-storage-backends/01-overview Use WP-CLI commands to test the connection, check the status, and view statistics of your MilliCache setup. ```bash 1# Quick test 2wp millicache test 3 4# Check status 5wp millicache status 6 7# View stats 8wp millicache stats ``` -------------------------------- ### Cache Read/Write Operations Source: https://millipress.com/docs/millicache/07-developers/01-architecture Provides examples for retrieving cached content using a request hash and storing new content with associated headers and flags. ```php 1$cache = $engine->cache(); 2 3// Check for cached content 4$result = $cache->get( $request_hash ); 5 6// Store content 7$cache->set( $request_hash, $content, $headers, $flags ); ``` -------------------------------- ### Get Millicache Help Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Commands to access help documentation for Millicache. Use `wp help millicache` for general help and `wp help millicache [command]` for specific command details. ```bash # General help wp help millicache ``` ```bash # Command-specific help wp help millicache clear wp help millicache config ``` -------------------------------- ### Redis Storage Operations Source: https://millipress.com/docs/millicache/07-developers/01-architecture Illustrates how to interact with the Redis storage layer for setting, getting, and deleting cache data. Includes checking connection status. ```php 1$storage = $engine->storage(); 2 3// Low-level operations 4$storage->set_cache( $key, $data, $flags ); 5$storage->get_cache( $key ); 6$storage->delete_cache( $key ); 7$storage->is_connected(); 8$storage->get_status(); ``` -------------------------------- ### Control Caching Decisions with Rules Source: https://millipress.com/docs/millicache/04-rules/01-introduction Examples of forcing cache bypass or forcing cache using the `do_cache` action. Use `do_cache(false)` to bypass and `do_cache(true)` to force caching. ```php ->then()->do_cache( false, 'Reason' ) // Bypass cache ->then()->do_cache( true ) // Force cache (override previous) ``` -------------------------------- ### Compound Conditions - OR Source: https://millipress.com/docs/millicache/04-rules/03-examples Implements OR logic for conditions, meaning the action executes if any of the specified URL patterns are matched. This example disables caching for dynamic pages matching specific URL segments. ```php Rules::create( 'mysite:any-match', 'php' ) ->when_any() ->request_url( '*/cart/*' ) ->request_url( '*/checkout/*' ) ->request_url( '*/account/*' ) ->then() // Runs if ANY condition matches ->do_cache( false, 'Dynamic page' ) ->register(); ``` -------------------------------- ### Install/Repair MilliCache Drop-in Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Installs or repairs the advanced-cache.php drop-in file for MilliCache. The `--force` option can be used to reinstall even if the file is already present. ```bash wp millicache drop [--force] ``` ```bash # Standard install/fix wp millicache drop ``` ```bash # Force reinstall wp millicache drop --force ``` -------------------------------- ### Get Network-Wide Cache Statistics via WP-CLI Source: https://millipress.com/docs/millicache/05-usage/30-multisite From the network admin context, run `wp millicache stats` without any site-specific arguments to view aggregated cache statistics for the entire network. ```bash wp millicache stats ``` -------------------------------- ### Flag Seasonal Products by Taxonomy Source: https://millipress.com/docs/millicache/04-rules/03-examples Use `has_term()` to apply rules based on product categories or tags. This example flags products belonging to the 'seasonal' category. ```php Rules::create( 'mysite:seasonal-flag', 'wp' ) ->on( 'template_redirect', 25 ) ->order( 10 ) ->when() ->is_singular( 'product' ) ->has_term( 'seasonal', 'product_cat' ) ->then() ->add_flag( 'promo:seasonal' ) ->register(); ``` -------------------------------- ### Audit Logging for Cache Clears Source: https://millipress.com/docs/millicache/07-developers/02-hooks-filters Implement audit logging by hooking into the 'millicache_cache_cleared' action. This example logs the user ID, name, method (expired or deleted), and timestamp of each cache clear event. ```php add_action( 'millicache_cache_cleared', function( $expire ) { $user = wp_get_current_user(); $method = $expire ? 'expired' : 'deleted'; log_audit_event( 'cache_cleared', [ 'user_id' => $user->ID, 'user_name' => $user->user_login, 'method' => $method, 'timestamp' => current_time( 'mysql' ), ] ); } ); ``` -------------------------------- ### Unregister and Override MilliCache Rules Source: https://millipress.com/docs/millicache/04-rules/02-built-in-rules Demonstrates how to unregister a built-in rule using Rules::unregister() and how to create a new rule with the same ID to override its behavior. This example overrides the logged-in user bypass to allow caching for subscribers. ```php add_action('template_redirect', function() { // Unregister a built-in rule to completely remove its behavior Rules::unregister( 'millicache:wp:const:doing-ajax' ); }); // Override the logged-in user bypass to allow caching for subscribers Rules::create( 'millicache:wp:logged-in' ) // Same ID as built-in ->on( 'template_redirect', 20 ) // Same hook & priority as built-in ->order( 10 ) // Higher order to run after built-in ->when() ->is_user_logged_in() ->custom( 'is-editor-or-higher', function() { return current_user_can( 'edit_posts' ); }) ->then() ->do_cache( false, 'Editor role or above' ) ->register(); ``` -------------------------------- ### Get Cache Statistics for a Specific Site via WP-CLI Source: https://millipress.com/docs/millicache/05-usage/30-multisite Retrieve cache statistics for a particular site using its URL or by filtering with a site flag prefix. The output can be formatted as JSON. ```bash # Stats for specific site wp millicache stats --url=site1.example.com # Filter by site flag prefix wp millicache stats --flag="2:*" ``` -------------------------------- ### View Current Configuration and Test Connection Source: https://millipress.com/docs/millicache/02-configuration/01-overview Use WP-CLI commands to view all settings with their sources, test the connection to the storage backend, and retrieve cache statistics. ```bash 1# All settings with sources 2wp millicache config get --show-source 3 4# Test connection 5wp millicache test 6 7# Cache statistics 8wp millicache stats ``` -------------------------------- ### Compound Conditions - NOT Source: https://millipress.com/docs/millicache/04-rules/03-examples Uses NOT logic to ensure an action is taken only when specific conditions are NOT met. This example disables caching for requests that are neither GET nor HEAD methods. ```php Rules::create( 'mysite:none-match', 'php' ) ->when_none() ->request_method( 'GET' ) ->request_method( 'HEAD' ) ->then() // Runs if NEITHER GET nor HEAD ->do_cache( false, 'Non-cacheable method' ) ->register(); ``` -------------------------------- ### Configure Development Environment Settings Source: https://millipress.com/docs/millicache/02-configuration/01-overview Set a very short cache TTL (1 minute) and enable debug headers for a development environment to quickly see changes and troubleshoot issues. ```php 1define( 'MC_CACHE_TTL', 60 ); // 1 minute 2define( 'MC_CACHE_DEBUG', true ); // Show debug headers ``` -------------------------------- ### Accessing the MilliCache Engine Source: https://millipress.com/docs/millicache/07-developers/01-architecture Demonstrates how to obtain an instance of the Engine singleton, either via the helper function or directly. Shows access to various subsystems. ```php 1// Recommended: Use the millicache() helper 2$engine = millicache(); 3 4// Or access Engine directly 5$engine = MilliCacheEngine::instance(); 6 7// Access subsystems 8$engine->storage(); // Redis connection 9$engine->flags(); // Flag manager 10$engine->config(); // Configuration 11$engine->options(); // Runtime overrides 12$engine->cache(); // Cache manager 13$engine->clear(); // Invalidation manager ``` -------------------------------- ### GET /wp-json/millicache/v1/status Source: https://millipress.com/docs/millicache/07-developers/03-api-reference Retrieves the current status of the Millicache plugin and its cache. ```APIDOC ## GET /wp-json/millicache/v1/status ### Description Get plugin and cache status. ### Method GET ### Endpoint /wp-json/millicache/v1/status ### Query Parameters - **network** (string) - Optional - Set to "true" for network stats in multisite. ### Response #### Success Response (200) - **plugin_name** (string) - The name of the plugin. - **version** (string) - The plugin version. - **cache** (object) - Cache statistics. - **entries** (integer) - Number of cache entries. - **size** (integer) - Total size of the cache in bytes. - **size_h** (string) - Human-readable cache size. - **storage** (object) - Storage details. - **connected** (boolean) - Whether storage is connected. - **version** (string) - Storage version. - **memory** (object) - Memory usage details. - **used** (integer) - Memory used in bytes. - **max** (integer) - Maximum memory available in bytes. - **dropin** (object) - Drop-in configuration status. - **status** (string) - Status of the drop-in (e.g., "symlink"). - **outdated** (boolean) - Whether the drop-in is outdated. - **settings** (object) - Plugin settings status. - **has_defaults** (boolean) - Whether settings are using defaults. - **has_backup** (boolean) - Whether a settings backup exists. ### Response Example ```json { "plugin_name": "millicache", "version": "1.0.0", "cache": { "entries": 142, "size": 2856432, "size_h": "2.7 MB" }, "storage": { "connected": true, "version": "7.2.4", "memory": { "used": 12500000, "max": 268435456 } }, "dropin": { "status": "symlink", "outdated": false }, "settings": { "has_defaults": false, "has_backup": true } } ``` ``` -------------------------------- ### Create and Register a Rule with MilliRules Source: https://millipress.com/docs/millicache/04-rules/01-introduction Demonstrates creating a rule with a specific ID, phase, priority, URL condition, and TTL action. Use this to define custom caching logic. ```php use MilliCacheDepsMilliRulesRules; Rules::create( 'mysite:example-rule', 'php' ) // Create rule with ID and phase ->order( 10 ) // Set priority ->when() // Start conditions ->request_url( '/news/*' ) // Match URL pattern ->then() // Start actions ->set_ttl( 1800 ) // Set 30-minute TTL ->register(); // Register the rule ``` -------------------------------- ### Cache Entry Flags for Invalidation Source: https://millipress.com/docs/millicache/05-usage/10-how-caching-works Provides examples of flags used to tag cached pages for targeted invalidation when content is updated. ```text Homepage: [home, archive:post] Single post: [post:123] Archives: [archive:category:5, archive:post] Author: [archive:author:1] ``` -------------------------------- ### Basic MilliCache Connection Source: https://millipress.com/docs/millicache/08-storage-backends/01-overview Configure the basic connection to a storage backend by defining the host and port. Ensure WP_CACHE is enabled. ```php 1// wp-config.php 2define( 'WP_CACHE', true ); 3 4define( 'MC_STORAGE_HOST', '127.0.0.1' ); 5define( 'MC_STORAGE_PORT', 6379 ); ``` -------------------------------- ### Reset Millicache settings to defaults Source: https://millipress.com/docs/millicache/07-developers/03-api-reference Revert all Millicache settings to their default values. This action is useful for troubleshooting or starting with a clean configuration. ```json 1{ 2 "action": "reset" 3} ``` -------------------------------- ### Import MilliCache Configuration Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Imports MilliCache settings from a JSON file. A backup is automatically created before importing. Settings can be merged with existing ones or replace them entirely. Confirmation can be skipped. ```bash wp millicache config import --file= [--merge] [--no-merge] [--yes] ``` ```bash # Import from file (merges by default) wp millicache config import --file=settings.json ``` ```bash # Replace all settings wp millicache config import --file=settings.json --no-merge ``` ```bash # Skip confirmation wp millicache config import --file=settings.json --yes ``` -------------------------------- ### Enable Gzip Compression for Cache Source: https://millipress.com/docs/millicache/02-configuration/02-reference Enables gzip compression of cached content. Requires the 'ext-zlib' PHP extension. ```php define( 'MC_CACHE_GZIP', true ); ``` -------------------------------- ### Remove Old Drop-in File Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Before installing MilliCache's drop-in, remove any existing advanced-cache.php file from another plugin to avoid conflicts. ```bash rm wp-content/advanced-cache.php ``` -------------------------------- ### Backup and Restore Millicache Settings Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Commands to manage Millicache configuration backups. Use `config backup` to create a manual backup, `config restore` to restore from the latest backup, `config export` to save settings to a file, and `config import` to load settings from a file. ```bash # Create a manual backup wp millicache config backup ``` ```bash # Restore from backup wp millicache config restore ``` ```bash # Export to file for external backup wp millicache config export --file=backup.json ``` ```bash # Import from file wp millicache config import --file=backup.json ``` -------------------------------- ### View Configuration via WP-CLI Source: https://millipress.com/docs/millicache/01-getting-started/20-installation Use this command to retrieve the current MilliCache configuration settings. This is an optional method for checking settings. ```bash wp millicache config get ``` -------------------------------- ### millicache_clear_cache_by_site_ids() Source: https://millipress.com/docs/millicache/07-developers/03-api-reference Clears cache for specific site IDs in a multisite setup. It can target a particular network and optionally expire entries instead of deleting them. ```APIDOC ## millicache_clear_cache_by_site_ids() ### Description Clear cache by site IDs (multisite). ### Parameters #### Path Parameters - **site_ids** (array) - Required - Array of site IDs - **network_id** (int) - Optional - Specific network ID (optional) - **expire** (bool) - Optional - Expire instead of delete ### Returns - **bool** - Success status ### Example ```php // Clear specific sites millicache_clear_cache_by_site_ids( [ 1, 2, 3 ] ); // Clear sites in specific network millicache_clear_cache_by_site_ids( [ 1, 2 ], 1 ); ``` ``` -------------------------------- ### Manage MilliCache Settings with WP-CLI Source: https://millipress.com/docs/millicache/02-configuration/01-overview Use WP-CLI commands to view all settings, set specific configuration values, and inspect the source of configuration values. ```bash 1# View all settings 2wp millicache config get 3 4# Set a value 5wp millicache config set cache.ttl 86400 6 7# See where values come from 8wp millicache config get --show-source ``` -------------------------------- ### Check Network Path to Redis Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Use `ping` to test basic network reachability and `traceroute` to identify potential network hops or bottlenecks between the server and Redis. ```bash ping redis-host traceroute redis-host ``` -------------------------------- ### Configure Cache TTL, Debugging, and Storage Host Source: https://millipress.com/docs/millicache/02-configuration/01-overview Define constants in wp-config.php to set the cache time-to-live, enable debug headers, and specify the storage host. ```php 1define( 'MC_CACHE_TTL', 86400 ); // 1 day 2define( 'MC_CACHE_DEBUG', true ); // Debug headers 3define( 'MC_STORAGE_HOST', 'redis' ); // Redis hostname ``` -------------------------------- ### Set Redis Authentication Credentials Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Update the username and password for Redis authentication within MilliCache. Ensure you use the correct credentials for your Redis setup. ```bash wp millicache config set storage.username "your-username" wp millicache config set storage.enc_password "your-password" ``` -------------------------------- ### Compound Conditions - AND (Default) Source: https://millipress.com/docs/millicache/04-rules/03-examples Demonstrates the default AND logic for combining conditions. The action only runs if all specified conditions (request method, URL pattern, cookie value) are met. ```php Rules::create( 'mysite:all-match', 'php' ) ->when() ->request_method( 'GET' ) ->request_url( '/shop/*' ) ->cookie( 'currency', 'EUR' ) ->then() // Only runs if ALL conditions match ->add_flag( 'shop:eur' ) ->register(); ``` -------------------------------- ### Configure Frequently Updated Content Settings Source: https://millipress.com/docs/millicache/02-configuration/01-overview Use a shorter cache TTL (1 hour) and grace period (1 day) for frequently updated content to ensure users see the latest information. ```php 1define( 'MC_CACHE_TTL', 3600 ); // 1 hour 2define( 'MC_CACHE_GRACE', 86400 ); // 1 day grace ``` -------------------------------- ### Gather Diagnostic Information for Support Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Collect status, configuration, and statistics in JSON format to provide comprehensive diagnostic data when seeking help. ```bash wp millicache status --format=json > status.json wp millicache config get --format=json > config.json wp millicache stats --format=json > stats.json ``` -------------------------------- ### Filter Allowed REST API Settings Actions Source: https://millipress.com/docs/millicache/07-developers/02-hooks-filters Customize the settings actions permitted through the REST API. For example, remove the 'restore' action to prevent accidental resets. ```php add_filter( 'millicache_rest_settings_allowed_actions', function( $actions ) { // Remove restore action $key = array_search( 'restore', $actions ); if ( $key !== false ) { unset( $actions[ $key ] ); } return $actions; } ); ``` -------------------------------- ### Backup MilliCache Configuration Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Creates a manual backup of the current MilliCache settings. Backups expire after 12 hours and are also created automatically before reset and import operations. ```bash wp millicache config backup ``` -------------------------------- ### Get Millicache plugin and cache status Source: https://millipress.com/docs/millicache/07-developers/03-api-reference Retrieve detailed information about the Millicache plugin's status, cache statistics, storage details, drop-in status, and settings. ```json 1{ 2 "plugin_name": "millicache", 3 "version": "1.0.0", 4 "cache": { 5 "entries": 142, 6 "size": 2856432, 7 "size_h": "2.7 MB" 8 }, 9 "storage": { 10 "connected": true, 11 "version": "7.2.4", 12 "memory": { 13 "used": 12500000, 14 "max": 268435456 15 } 16 }, 17 "dropin": { 18 "status": "symlink", 19 "outdated": false 20 }, 21 "settings": { 22 "has_defaults": false, 23 "has_backup": true 24 } 25} ``` -------------------------------- ### Run Diagnostic Commands Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Use these WP-CLI commands to check the overall status, test Redis connectivity, view cache statistics, and inspect configuration sources. ```bash wp millicache status wp millicache test wp millicache stats wp millicache config get --show-source ``` -------------------------------- ### Target Pages with Specific Gutenberg Blocks Source: https://millipress.com/docs/millicache/04-rules/03-examples Use `has_block()` to apply rules to pages containing specific Gutenberg blocks. This example flags pages with a pricing table block. ```php Rules::create( 'mysite:pricing-flag', 'wp' ) ->on( 'template_redirect', 25 ) ->order( 10 ) ->when() ->is_singular() ->has_block( 'acme/pricing-table' ) ->then() ->add_flag( 'block:pricing' ) ->register(); ``` -------------------------------- ### Inspect MilliCache Configuration Sources Source: https://millipress.com/docs/millicache/05-usage/30-multisite This command helps identify where MilliCache settings are being loaded from. Verify that configuration files are named correctly and that constants are set as expected. ```bash wp millicache config get --show-source ``` -------------------------------- ### API Rate Limiting Support Source: https://millipress.com/docs/millicache/04-rules/03-examples Applies a short TTL and grace period to API GET requests matching a specific URL pattern. This is useful for rate-limiting API responses. ```php Rules::create( 'mysite:api-ttl', 'php' ) ->order( 10 ) ->when() ->request_url( '/api/*' ) ->request_method( 'GET' ) ->then() ->set_ttl( 60 ) // 1 minute ->set_grace( 300 ) // 5 minute grace ->register(); ``` -------------------------------- ### Prefix Flags with Current Site - PHP Source: https://millipress.com/docs/millicache/03-cache-flags/02-built-in-flags Use millicache_get_flag_prefix to automatically prefix flags with the current site's ID in multisite or multi-network setups. This ensures cache isolation. ```php 1// Prefix flags with the current site's prefix 2$prefix = millicache_get_flag_prefix( ['home', 'post:123'] ); 3// Returns: ['home', 'post:123'] (single site), ['2:home', '2:post:123'] (multisite), or ['1:2:home', '1:2:post:123'] (multi-network) ``` -------------------------------- ### Troubleshooting Authentication Failed Errors Source: https://millipress.com/docs/millicache/08-storage-backends/01-overview Resolve 'NOAUTH Authentication required' errors by correctly setting the `MC_STORAGE_USERNAME` and `MC_STORAGE_PASSWORD` constants in your configuration. ```php 1define( 'MC_STORAGE_USERNAME', 'your-username' ); // omit if using default user 2define( 'MC_STORAGE_PASSWORD', 'your-password' ); ``` -------------------------------- ### Batch Clear Related Cache Items Source: https://millipress.com/docs/millicache/05-usage/20-cache-clearing Group related cache clearing actions together using flags. This example clears a post, the home page, and the post archive simultaneously. ```php 1// Clear post and its relationships 2$flags = [ "post:{$post_id}", 'home', 'archive:post', ]; 7millicache_clear_cache_by_flags( $flags ); ``` -------------------------------- ### Configure Firewall for Redis Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues If Redis is inaccessible, check your firewall rules. Use `ufw status` to view current rules and `ufw allow 6379/tcp` to open the port if necessary. ```bash sudo ufw status # Allow if needed sudo ufw allow 6379/tcp ``` -------------------------------- ### POST /wp-json/millicache/v1/settings Source: https://millipress.com/docs/millicache/07-developers/03-api-reference Performs settings actions, including resetting to defaults or restoring from a backup. ```APIDOC ## POST /wp-json/millicache/v1/settings ### Description Perform settings actions. Requires authentication via `X-WP-Nonce` header. ### Method POST ### Endpoint /wp-json/millicache/v1/settings ### Request Body - **action** (string) - Required - The settings action to perform. Possible values: `reset`, `restore`. ### Request Example ```json { "action": "reset" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the action was successful. - **message** (string) - A message describing the result of the action. - **action** (string) - The action that was performed. - **timestamp** (integer) - The timestamp when the action occurred. ### Response Example ```json { "success": true, "message": "Settings reset successfully.", "action": "reset", "timestamp": 1699900000 } ``` ``` -------------------------------- ### Keep Bootstrap Rules Simple Source: https://millipress.com/docs/millicache/04-rules/03-examples Demonstrates a simple string match for a bootstrap rule's condition, emphasizing the need for fast, non-complex logic in the bootstrap phase. ```php ->when()->request_url( '/api/*' ) ``` ```php ->when()->custom( 'complex', function() { // Loading files, database, etc. defeats the purpose } ) ``` -------------------------------- ### Restrict Cache Clearing by Role Source: https://millipress.com/docs/millicache/07-developers/02-hooks-filters Use the `millicache_clear_cache_capability` filter to control which user roles can clear the cache. This example restricts clearing to 'manage_options' capability in production environments and 'edit_posts' capability in staging/development. ```php add_filter( 'millicache_clear_cache_capability', function( $capability ) { // Only allow on staging/development if ( defined( 'WP_ENV' ) && WP_ENV === 'production' ) { return 'manage_options'; // Admins only in production } return 'edit_posts'; // Editors can clear on staging } ); ``` -------------------------------- ### Verify DNS Resolution for Redis Host Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Ensure that the hostname for your Redis server resolves correctly to an IP address. Use the `host` command for DNS lookups. ```bash host redis-host ``` -------------------------------- ### Notify CDN on Cache Clear Action Source: https://millipress.com/docs/millicache/07-developers/02-hooks-filters Hook into the 'millicache_cache_cleared_by_flags' action to notify a CDN when cache is cleared based on specific flags. This example converts MilliCache flags to CDN tags and purges them. ```php add_action( 'millicache_cache_cleared_by_flags', function( $flags, $expire ) { // Convert MilliCache flags to CDN tags $cdn_tags = array_map( function( $flag ) { return 'millicache-' . sanitize_title( $flag ); }, $flags ); // Purge CDN cdn_purge_by_tags( $cdn_tags ); }, 10, 2 ); ``` -------------------------------- ### Configure Redis Host via Unix Socket Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Improve performance by configuring MilliCache to use a Unix socket for connecting to Redis. ```php define( 'MC_STORAGE_HOST', '/var/run/redis/redis.sock' ); ``` -------------------------------- ### Custom Flags for ACF Fields and Cache Clearing Source: https://millipress.com/docs/millicache/07-developers/02-hooks-filters Create custom flags for requests based on Advanced Custom Fields (ACF) values, and trigger cache clears when these fields change. This example adds a 'acf:dynamic' flag if 'enable_dynamic_content' is true and clears cache for this flag when the field is saved. ```php add_filter( 'millicache_flags_for_request', function( $flags ) { if ( ! function_exists( 'get_field' ) ) { return $flags; } // Add a flag for pages with a specific ACF field if ( is_singular() && get_field( 'enable_dynamic_content' ) ) { $flags[] = 'acf:dynamic'; } return $flags; } ); // Clear when the ACF field changes add_action( 'acf/save_post', function( $post_id ) { if ( get_field( 'enable_dynamic_content', $post_id ) ) { millicache_clear_cache_by_flags( [ 'acf:dynamic' ] ); } } ); ``` -------------------------------- ### Recommended Redis Server Configuration Source: https://millipress.com/docs/millicache/08-storage-backends/01-overview Apply these settings to your Redis server for optimal WordPress caching performance, including memory management and persistence options. ```redis 1# Memory allocation (adjust based on your needs) 2maxmemory 256mb 3maxmemory-policy allkeys-lru 4 5# Persistence (optional - cache can be regenerated) 6save "" 7appendonly no 8 9# Performance 10tcp-keepalive 300 11timeout 0 12 13# Security (if exposed to network) 14bind 127.0.0.1 15requirepass your-strong-password ``` -------------------------------- ### Cache Key Generation Formula Source: https://millipress.com/docs/millicache/05-usage/10-how-caching-works Shows the components used to generate a unique cache key for looking up content in Redis. ```text Cache Key = hash( URL + filtered_cookies + unique_vars ) ``` -------------------------------- ### Troubleshooting Connection Refused Errors Source: https://millipress.com/docs/millicache/08-storage-backends/01-overview Diagnose and resolve 'Connection refused' errors by verifying the server status, host/port, and firewall rules. Use `redis-cli` for manual testing. ```bash 1# Check if Redis is running 2redis-cli ping 3 4# Check listening port 5netstat -tlnp | grep 6379 6 7# Test connection manually 8redis-cli -h 127.0.0.1 -p 6379 ping ``` -------------------------------- ### Adjust Cache Timing with Rules Source: https://millipress.com/docs/millicache/04-rules/01-introduction Set the Time To Live (TTL) for cache entries or the grace period for stale content using `set_ttl` and `set_grace` actions. ```php ->then()->set_ttl( 3600 ) // Cache for 1 hour ->then()->set_grace( 86400 ) // Allow stale for 1 day ``` -------------------------------- ### Enable Persistent Redis Connections Source: https://millipress.com/docs/millicache/02-configuration/02-reference Enables persistent connections to Redis, which can reduce connection overhead. Requires proper server configuration. ```php define( 'MC_STORAGE_PERSISTENT', true ); ``` -------------------------------- ### Define and Register Custom Rule Actions in PHP Source: https://millipress.com/docs/millicache/07-developers/01-architecture Extend the MilliRules engine by creating custom action classes that implement the `MilliRulesContractsAction` interface. Register these actions with the `Rules::add` method to define custom caching rules. ```php // Create a custom action class MyCustomAction implements MilliRulesContractsAction { public function execute( $context ) { // Custom logic } } // Register with MilliRules use MilliRulesRules; Rules::add( [ 'id' => 'mysite:custom', 'condition' => [ 'request:path', 'matches', '/special/*' ], 'actions' => [ new MyCustomAction() ], 'order' => 10, 'phase' => 'wp', ] ); ``` -------------------------------- ### Set Different TTLs by Content Type Source: https://millipress.com/docs/millicache/04-rules/03-examples Configure distinct Time-To-Live (TTL) values for different URL patterns. Use this to cache news for a shorter duration and documentation for a longer period. ```php Rules::create( 'mysite:news-ttl', 'php' ) ->order( 10 ) ->when() ->request_url( '/news/*' ) ->then() ->set_ttl( 900 ) // 15 minutes ->register(); Rules::create( 'mysite:docs-ttl', 'php' ) ->order( 10 ) ->when() ->request_url( '/docs/*' ) ->then() ->set_ttl( 604800 ) // 1 week ->register(); ``` -------------------------------- ### Configure High-Traffic Site Settings Source: https://millipress.com/docs/millicache/02-configuration/01-overview Set a longer cache TTL (7 days) and grace period (30 days) for high-traffic sites, ensuring content is served from cache more frequently. ```php 1define( 'MC_CACHE_TTL', 604800 ); // 7 days 2define( 'MC_CACHE_GRACE', 2592000 ); // 30 days grace 3define( 'MC_CACHE_GZIP', true ); ``` -------------------------------- ### Deploy Millicache Commands Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Commands to use after deploying Millicache. Use `drop` to forcefully remove the cache, `test` to check connectivity, and `clear` to empty the cache. ```bash wp millicache drop --force ``` ```bash wp millicache test ``` ```bash wp millicache clear ``` -------------------------------- ### Set Cache Time-To-Live (TTL) Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Reduce memory usage by setting a shorter Time-To-Live for cache entries. ```php define( 'MC_CACHE_TTL', 3600 ); // 1 hour ``` -------------------------------- ### Check Specific Site Cache Flags Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Verify cache flag prefixes for individual sites in a multisite environment to ensure cache isolation. ```bash wp millicache stats --flag="1:*" # Site 1 ``` ```bash wp millicache stats --flag="2:*" # Site 2 ``` -------------------------------- ### Test MilliCache Redis Connection via WP-CLI Source: https://millipress.com/docs/millicache/01-getting-started/20-installation Execute this WP-CLI command to perform a series of tests on the Redis connection, including ping, write, read, and delete operations. ```bash wp millicache test ``` -------------------------------- ### Log All Registered MilliCache Rules Source: https://millipress.com/docs/millicache/04-rules/02-built-in-rules Iterate through all registered rules using Rules::all() and log their ID, order, and phase. This is useful for understanding the current rule configuration. ```php use MilliCacheDepsMilliRulesRules; // Log all rules foreach ( Rules::all() as $rule ) { error_log( sprintf( 'Rule: %s (order: %d, phase: %s)', $rule['id'], $rule['order'], $rule['phase'] ) ); } ``` -------------------------------- ### Enable WordPress Caching and Connect to Redis Source: https://millipress.com/docs/millicache/02-configuration/01-overview Add these constants to your wp-config.php file to enable WordPress caching and configure connection details for Redis. ```php 1// Required - enables WordPress caching 2define( 'WP_CACHE', true ); 3 4// Optional - Connect to Redis (adjust for your setup) 5define( 'MC_STORAGE_HOST', '127.0.0.1' ); 6define( 'MC_STORAGE_PORT', 6379 ); ``` -------------------------------- ### Network-Wide Cache Settings via Constants Source: https://millipress.com/docs/millicache/05-usage/30-multisite Configure cache settings that apply to all sites in the network by defining constants in wp-config.php. ```php define( 'MC_CACHE_TTL', 86400 ); define( 'MC_STORAGE_HOST', 'redis.example.com' ); ``` -------------------------------- ### Enable WP_CACHE in wp-config.php Source: https://millipress.com/docs/millicache/05-usage/30-multisite This constant must be defined to enable caching. Ensure it is set to true. ```php define( 'WP_CACHE', true ); ``` -------------------------------- ### Settings action response Source: https://millipress.com/docs/millicache/07-developers/03-api-reference The response structure confirming the success or failure of a settings action, such as reset or restore, including the action performed and a timestamp. ```json 1{ 2 "success": true, 3 "message": "Settings reset successfully.", 4 "action": "reset", 5 "timestamp": 1699900000 6} ``` -------------------------------- ### MilliCache Connection using Unix Socket Source: https://millipress.com/docs/millicache/08-storage-backends/01-overview Configure connection to a storage backend using a Unix socket. The port is ignored when using sockets. ```php 1define( 'MC_STORAGE_HOST', '/var/run/redis/redis.sock' ); 2define( 'MC_STORAGE_PORT', 0 ); // Ignored for sockets ``` -------------------------------- ### Restore Millicache settings from backup Source: https://millipress.com/docs/millicache/07-developers/03-api-reference Load previously saved Millicache settings from a backup. This is helpful for recovering from accidental misconfigurations or reverting to a known good state. ```json 1{ 2 "action": "restore" 3} ``` -------------------------------- ### Check MilliCache Status via WP-CLI Source: https://millipress.com/docs/millicache/01-getting-started/20-installation Run this WP-CLI command to view the current status and configuration of MilliCache, including version, cache status, and storage connection. ```bash wp millicache status ``` -------------------------------- ### wp millicache config set Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Set a configuration value. Values are automatically coerced to appropriate types. ```APIDOC ## wp millicache config set ### Description Set a configuration value. ### Method `wp millicache config set` ### Parameters #### Arguments - `` (string) - The configuration key to set - `` (string) - The value to set for the configuration key ### Examples ```bash # Set TTL wp millicache config set cache.ttl 3600 # Set boolean wp millicache config set cache.debug true # Set array (JSON format) wp millicache config set cache.nocache_paths '["/cart/*", "/checkout/*"]' # Set password (automatically encrypted, masked in output) wp millicache config set storage.enc_password "secret" ``` Note: Settings defined via constants cannot be overridden via CLI. ``` -------------------------------- ### Restore MilliCache Configuration Source: https://millipress.com/docs/millicache/06-wp-cli/01-commands Restores MilliCache settings from the most recent backup. ```bash wp millicache config restore ``` -------------------------------- ### Test Request Flow with cURL Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Use cURL to test request flow, check for MilliCache headers, and measure the time taken for multiple requests to assess caching effectiveness. ```bash # With headers curl -v https://example.com/ 2>&1 | grep -i millicache # Multiple requests to test caching for i in {1..3}; do curl -s -o /dev/null -w "Request $i: %{http_code} in %{time_total}sn" https://example.com/ done ``` -------------------------------- ### Test Redis Authentication Directly Source: https://millipress.com/docs/millicache/09-troubleshooting/01-common-issues Use `redis-cli` to test Redis connection and authentication using the configured username and password. This helps isolate authentication issues. ```bash # With a named user (Redis ACL) redis-cli -u "redis://your-username:your-password@127.0.0.1:6379" ping # With the default user (password only) redis-cli -a "your-password" ping ``` -------------------------------- ### Configure Restrict Content Pro Cache Exceptions Source: https://millipress.com/docs/millicache/09-troubleshooting/02-faq Define cookies to exclude from caching when using Restrict Content Pro. This ensures that membership access and user-specific content are handled correctly. ```php define( 'MC_CACHE_NOCACHE_COOKIES', [ 'wp-*pass*', 'rcp_*', ] ); ``` -------------------------------- ### Clear All Cache via WP-CLI Source: https://millipress.com/docs/millicache/05-usage/30-multisite Execute `wp millicache clear` without any arguments from the main site context to clear the cache for all sites across all networks. ```bash wp millicache clear ```