Skip to content

Instantly share code, notes, and snippets.

@mrcave
Last active January 15, 2025 13:52
Show Gist options
  • Save mrcave/7cdf6707273252de04094d4ed8d0d43c to your computer and use it in GitHub Desktop.
Save mrcave/7cdf6707273252de04094d4ed8d0d43c to your computer and use it in GitHub Desktop.
Clear NGINX page cache when WooCommerce product inventory levels are changed (only tested on GridPane with Redis page caching enabled)
//clear entire cache when stock is reduced or replenished
function clear_cache_when_stock_changes( $order ) {
if(class_exists('PhpRedis_Purger') || class_exists('Predis_Purger')){
global $nginx_purger;
$nginx_purger->purge_all();
}
}
add_action( 'woocommerce_reduce_order_stock', 'clear_cache_when_stock_changes', 10, 1 );
add_action( 'woocommerce_restore_order_stock', 'clear_cache_when_stock_changes', 10, 1 );
//only clear product page caches when stock changes
function clear_product_page_caches_when_stock_changes( $order ) {
if(class_exists('PhpRedis_Purger') || class_exists('Predis_Purger')){
if($order){
global $nginx_purger;
foreach ( $order->get_items() as $item_id => $item ) {
$product_id = $item->get_product_id();
$nginx_purger->purge_post( $product_id );
}
}
}
}
add_action( 'woocommerce_reduce_order_stock', 'clear_product_page_caches_when_stock_changes', 10, 1 );
add_action( 'woocommerce_restore_order_stock', 'clear_product_page_caches_when_stock_changes', 10, 1 );
@razorfrog
Copy link

Thanks for this! Looks like an error is thrown if the nginx-helper plugin is deactivated. I'll add a check for that on Monday.

FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught Error: Call to a member function purge_all() on null

@mrcave
Copy link
Author

mrcave commented Oct 17, 2020

Ya this hasn't been tested rigorously, but that was actually something I originally had in there and accidentally deleted when troubleshooting. There are a few ways to check for presence of the active plugin. I prefer to look at classes and have added that back in, but you can also check this with is_plugin_active()

@graphiclux
Copy link

I have tried this on my server with the GridPane framework and it does not work (I have tried both and neither work).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment