wp-media / wp-rocket-helpers

🚀 Helper plugins for specific use cases with WP Rocket. ☝️ TEST BEFORE USE! ☝️
https://wp-rocket.me/support/
GNU General Public License v2.0
202 stars 68 forks source link

Cloudflare cache purge on purchase #37

Open FreshLondon opened 4 years ago

FreshLondon commented 4 years ago

Hey folks!

Had an issue where the Cloudflare cache wasn't purging when a product was sold, meaning the inventory could go to 0 and still the item would be listed as 'available' on the site.

I know clearing the entire cache is not ideal for every situation, especially large sites, and maybe you could improve on my below code for other users?

function clean_product_cache_after_order($order_id) {
    try {
        rocket_clean_domain();
        return true;
    } catch (Exception $e) {
        error_log('Cloudflare purge failed during order #' . $order_id, $e->getMessage());
    }
}

// hide or show these as you see fit:
add_action('woocommerce_order_status_pending', __NAMESPACE__ . '\clean_product_cache_after_order');
// add_action( 'woocommerce_order_status_failed', __NAMESPACE__ . '\clean_product_cache_after_order' );
// add_action( 'woocommerce_order_status_on-hold', __NAMESPACE__ . '\clean_product_cache_after_order' );
add_action('woocommerce_order_status_processing', __NAMESPACE__ . '\clean_product_cache_after_order');
add_action('woocommerce_order_status_completed', __NAMESPACE__ . '\clean_product_cache_after_order');
// add_action( 'woocommerce_order_status_refunded', __NAMESPACE__ . '\clean_product_cache_after_order' );
// add_action( 'woocommerce_order_status_cancelled', __NAMESPACE__ . '\clean_product_cache_after_order' );

hope it helps, this works perfectly for me but its only a small site so a full cache clear is not an issue. 👍