### Install Memcached Object Cache Plugin Source: https://github.com/automattic/batcache/blob/master/readme.txt This is a placeholder for installing the Memcached Object Cache plugin. Ensure you have the PECL memcached extension installed on your server. ```php ``` -------------------------------- ### Batcache Cache Key with Request Method Source: https://github.com/automattic/batcache/blob/master/readme.txt This change in version 1.2 adds the REQUEST_METHOD to the cache keys. This prevents GET requests from receiving bodyless HEAD responses and invalidates the entire cache upon upgrade. ```php if ( defined( 'BATCACHE_ENABLE_CORS_GET' ) && BATCACHE_ENABLE_CORS_GET && 'GET' === $request_method ) { $cache_key = 'batcache:' . $_SERVER['REQUEST_METHOD'] . ':' . $cache_key; } else { $cache_key = 'batcache:' . $cache_key; } ``` -------------------------------- ### Add Custom Cache Key Components with Batcache Source: https://context7.com/automattic/batcache/llms.txt Inject arbitrary scalar values into the cache key to create distinct cached variants. Useful for simple flag-based differentiation evaluated before WordPress loads. ```php // In advanced-cache.php, after $batcache is instantiated: // Serve different caches to logged-in vs. logged-out users // (based solely on the presence of a WordPress auth cookie) $is_logged_in = false; foreach (array_keys($_COOKIE) as $cookie_name) { if (substr($cookie_name, 0, 14) === 'wordpress_logged_in') { $is_logged_in = true; break; } } $batcache->unique['auth'] = $is_logged_in; // Cache separate copies for a custom A/B test cookie $batcache->unique['ab_group'] = isset($_COOKIE['ab_group']) ? $_COOKIE['ab_group'] : 'control'; // Differentiate by subdomain $batcache->unique['subdomain'] = strtolower( explode('.', $_SERVER['HTTP_HOST'])[0] ); ``` -------------------------------- ### Batcache Configuration in advanced-cache.php Source: https://github.com/automattic/batcache/blob/master/readme.txt This snippet shows the beginning of the advanced-cache.php file, where you can tweak Batcache options. Ensure Memcached is running and accessible. ```php 300, // Seconds before a cached page expires 'remote' => 0, // 1 = replicate buffers to remote datacenters 'times' => 2, // Minimum page hits before caching begins 'seconds' => 120, // Hit-counting window in seconds 'group' => 'batcache', // Memcached group name (change = instant flush) 'unique' => array(), // Extra key components for cache variants 'vary' => array(), // Anonymous functions for variant detection 'headers' => array(), // Custom headers sent with every cached response 'cache_redirects' => false, // Cache HTTP redirects (301/302/307 etc.) 'use_stale' => true, // Serve expired cache while regenerating 'uncached_headers' => array('transfer-encoding'), 'debug' => true, // Append HTML comment with timing info 'cache_control' => true, // Emit Last-Modified and Cache-Control headers 'noskip_cookies' => array('wordpress_test_cookie'), 'cacheable_origin_hostnames'=> array(), // Whitelisted CORS origins 'ignored_query_args' => array(), // Query params excluded from cache key ); ``` -------------------------------- ### Register Cache Variants with vary_cache_on_function() Source: https://context7.com/automattic/batcache/llms.txt Use this function to register anonymous functions that generate cache keys based on visitor context. The function string is evaluated with eval and must reference a $_ superglobal. Dangerous keywords are blocked. ```php vary_cache_on_function( 'return (bool) preg_match("/Mobile|Android|iPhone/i", $_SERVER["HTTP_USER_AGENT"]);' ); ``` ```php vary_cache_on_function( 'return (bool) preg_match("/feedburner/i", $_SERVER["HTTP_USER_AGENT"]);' ); ``` ```php vary_cache_on_function( 'return isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]) ? substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2) : "en";' ); ``` ```php vary_cache_on_function( 'return isset($_COOKIE["user_country"]) ? $_COOKIE["user_country"] : "default";' ); ``` -------------------------------- ### Configure Batcache Settings in wp-config.php Source: https://context7.com/automattic/batcache/llms.txt Define Batcache settings in wp-config.php before the "That's all" line to control caching behavior, including cache age, hit counts, and debug output. ```php // wp-config.php — place BEFORE the "That's all" line define('WP_CACHE', true); // Override default Batcache settings via the global array $batcache = array( 'max_age' => 300, // Cache pages for 5 minutes 'times' => 2, // Only cache after 2 hits … 'seconds' => 120, // … within 120 seconds 'debug' => false, // Hide HTML comment with timing info 'cache_redirects' => true, // Also cache 301/302 redirects 'use_stale' => true, // Serve stale content while regenerating 'group' => 'batcache', // Change to flush the entire cache ); ``` -------------------------------- ### Whitelist CORS Origins with Batcache Source: https://context7.com/automattic/batcache/llms.txt Allows Batcache to cache responses for cross-origin requests from specific trusted hosts. Only origins using http/https schemes on standard ports (80/443) can be whitelisted. ```php // In advanced-cache.php or wp-config.php: $batcache = array( 'cacheable_origin_hostnames' => array( 'app.example.com', 'partner.example.org', 'staging.example.net', ), ); // At runtime Batcache calls is_cacheable_origin() internally: // $batcache->is_cacheable_origin('https://app.example.com') → true // $batcache->is_cacheable_origin('https://evil.com') → false (not in list) // $batcache->is_cacheable_origin('ftp://app.example.com') → false (bad scheme) // $batcache->is_cacheable_origin('https://app.example.com:8080') → false (non-standard port) ``` -------------------------------- ### Batcache Stats in Page Source Source: https://github.com/automattic/batcache/blob/master/readme.txt After enabling Batcache and reloading a page, you should see these stats just above the closing tag in your page source. This confirms Batcache is active and serving content. ```html ``` -------------------------------- ### Custom Batcache Statistics Logging to StatsD Source: https://context7.com/automattic/batcache/llms.txt Replace the default batcache_stats() implementation to send metrics to a different backend, such as StatsD. The default implementation writes TSV records to dated log files. ```php // Custom implementation — send stats to StatsD instead of flat files if (!function_exists('batcache_stats')) { function batcache_stats($name, $value, $num = 1, $today = false, $hour = false) { // $name = 'batcache' // $value = 'total_cached_views' | 'total_page_views' | 'cookie_skip' | // 'origin_skip' | 'x_wp_nonce_skip' $socket = @fsockopen('udp://statsd.internal', 8125, $errno, $errstr, 1); if ($socket) { $metric = rawurldecode($value); // value is rawurlencoded by callers $payload = "batcache.{$metric}:{$num}|c"; fwrite($socket, $payload); fclose($socket); } } } // Batcache calls this automatically at two points: // 1. On a cache HIT → batcache_stats('batcache', 'total_cached_views') // 2. On a cache MISS → batcache_stats('batcache', 'total_page_views') // 3. On cookie skip → batcache_stats('batcache', 'cookie_skip') // 4. On origin skip → batcache_stats('batcache', 'origin_skip') // 5. On nonce skip → batcache_stats('batcache', 'x_wp_nonce_skip') ``` -------------------------------- ### vary_cache_on_function() — Cache Variants Source: https://context7.com/automattic/batcache/llms.txt Registers an anonymous function (as a string) whose return value is added to the cache key. This allows Batcache to store separate copies of a page for different visitors or contexts based on dynamic conditions. ```APIDOC ## `vary_cache_on_function()` — Cache Variants Registers an anonymous function (as a string) whose return value is added to the cache key, allowing Batcache to store separate copies of a page for different visitors or contexts. The function string is evaluated with `eval` and must reference at least one `$_` superglobal. Dangerous keywords (`include`, `require`, `eval`, `echo`, `socket`, etc.) are blocked. ### Usage Example ```php // Variant: cache separately for mobile vs. desktop user agents vary_cache_on_function( 'return (bool) preg_match("/Mobile|Android|iPhone/i", $_SERVER["HTTP_USER_AGENT"]);' ); // Variant: cache separately for Feedburner crawlers vary_cache_on_function( 'return (bool) preg_match("/feedburner/i", $_SERVER["HTTP_USER_AGENT"]);' ); // Variant: cache separately based on the Accept-Language header vary_cache_on_function( 'return isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]) ? substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2) : "en";' ); // Variant: distinguish logged-out users by country via a custom cookie vary_cache_on_function( 'return isset($_COOKIE["user_country"]) ? $_COOKIE["user_country"] : "default";' ); ``` ``` -------------------------------- ### Exclude Query Parameters from Batcache Keys Source: https://context7.com/automattic/batcache/llms.txt Prevent tracking or analytics query parameters from creating separate cache entries for effectively the same page. This ensures that URLs with different tracking parameters share a single cache entry. ```php // In advanced-cache.php, after $batcache is instantiated: $batcache->ignored_query_args = array( 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', '_ga', 'mc_eid', ); // Now https://example.com/page/?utm_source=twitter // and https://example.com/page/?utm_source=facebook // share the same cache entry as https://example.com/page/ ``` -------------------------------- ### Programmatic Cache Invalidation with batcache_clear_url() Source: https://context7.com/automattic/batcache/llms.txt This function increments the version counter for a specific URL in Memcached, marking its cache entry as stale. It's the primary method for invalidating cache entries programmatically. ```php batcache_clear_url('https://example.com/my-updated-page/'); ``` ```php function my_bulk_import_complete() { $home = trailingslashit(get_option('home')); batcache_clear_url($home); batcache_clear_url($home . 'feed/'); } add_action('import_end', 'my_bulk_import_complete'); ``` ```php add_action('updated_post_meta', function ($meta_id, $post_id, $meta_key) { if ($meta_key === '_my_custom_field') { batcache_clear_url(get_permalink($post_id)); } }, 10, 3); ``` -------------------------------- ### batcache_cancel() — Abort Caching for a Request Source: https://context7.com/automattic/batcache/llms.txt Cancels the output buffer for the current request, preventing the response from being stored in Memcached. Use this when a page should never be cached, such as for personalized content or payment confirmation pages. ```APIDOC ## `batcache_cancel()` — Abort Caching for a Request Cancels the output buffer for the current request so the response is never stored in Memcached. Call this inside a WordPress hook or template when a page must never be cached (e.g., personalised content, payment confirmation pages). ### Usage Example ```php // In a plugin or theme's functions.php: // Never cache the WooCommerce cart, checkout, or account pages add_action('template_redirect', function () { if (is_cart() || is_checkout() || is_account_page()) { batcache_cancel(); } }); // Never cache pages for users who have items in their session cart add_action('wp', function () { if (WC()->cart && WC()->cart->get_cart_contents_count() > 0) { batcache_cancel(); } }); // Never cache search result pages add_action('template_redirect', function () { if (is_search()) { batcache_cancel(); } }); ``` ``` -------------------------------- ### Cancel Caching for a Request with batcache_cancel() Source: https://context7.com/automattic/batcache/llms.txt Call this function within a WordPress hook or template to prevent the current response from being stored in Memcached. Useful for pages with personalized content or payment confirmations. ```php add_action('template_redirect', function () { if (is_cart() || is_checkout() || is_account_page()) { batcache_cancel(); } }); ``` ```php add_action('wp', function () { if (WC()->cart && WC()->cart->get_cart_contents_count() > 0) { batcache_cancel(); } }); ``` ```php add_action('template_redirect', function () { if (is_search()) { batcache_cancel(); } }); ``` -------------------------------- ### Automatic Post Cache Invalidation with batcache_post() Source: https://context7.com/automattic/batcache/llms.txt This is a WordPress action callback for 'clean_post_cache'. It automatically clears the cache for the home page, home feed, and the post's permalink when a post is published or trashed. It can be extended to clear custom archive pages. ```php $post_id = 42; $post = get_post($post_id); batcache_post($post_id, $post); ``` ```php add_action('clean_post_cache', function ($post_id, $post) { if ($post && get_post_type($post_id) === 'product') { batcache_clear_url(home_url('/shop/')); } }, 20, 2); ``` -------------------------------- ### batcache_post() — Automatic Post Cache Invalidation Source: https://context7.com/automattic/batcache/llms.txt A WordPress action callback hooked to `clean_post_cache`. When a post is published or trashed, this function automatically clears the cache for the home page, the home feed, and the post's permalink. ```APIDOC ## `batcache_post()` — Automatic Post Cache Invalidation WordPress action callback hooked to `clean_post_cache`. When a post is published or trashed, it clears the cached home page, the home feed, and the post's own permalink. Loaded automatically when `batcache.php` is installed as an MU-plugin. ### Usage Example ```php // batcache.php registers this automatically: // add_action('clean_post_cache', 'batcache_post', 10, 2); // Manual invocation (e.g., from WP-CLI or a custom script): $post_id = 42; $post = get_post($post_id); batcache_post($post_id, $post); // Clears: home page, home/feed/, and get_permalink(42) // Extend the hook to also clear a custom archive page: add_action('clean_post_cache', function ($post_id, $post) { if ($post && get_post_type($post_id) === 'product') { batcache_clear_url(home_url('/shop/')); } }, 20, 2); ``` ``` -------------------------------- ### batcache_clear_url() — Programmatic Cache Invalidation Source: https://context7.com/automattic/batcache/llms.txt Increments the version counter for a specific URL in Memcached, causing Batcache to regenerate the cached entry on the next request. This is the primary method for invalidating specific cached pages. ```APIDOC ## `batcache_clear_url()` — Programmatic Cache Invalidation Increments the version counter for a specific URL in Memcached, causing Batcache to treat any existing cached entry for that URL as stale and regenerate it on the next request. This is the primary invalidation primitive; `batcache_post()` calls it automatically on post publish/trash. ### Usage Example ```php // Requires batcache.php to be loaded as an MU-plugin. // Invalidate a single URL immediately batcache_clear_url('https://example.com/my-updated-page/'); // Invalidate the home page and its feed after a bulk import function my_bulk_import_complete() { $home = trailingslashit(get_option('home')); batcache_clear_url($home); batcache_clear_url($home . 'feed/'); } add_action('import_end', 'my_bulk_import_complete'); // Invalidate a post's URL when a custom field is updated add_action('updated_post_meta', function ($meta_id, $post_id, $meta_key) { if ($meta_key === '_my_custom_field') { batcache_clear_url(get_permalink($post_id)); } }, 10, 3); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.