diff --git a/cloudflare.loader.php b/cloudflare.loader.php index 65a6ed7d..099821d4 100644 --- a/cloudflare.loader.php +++ b/cloudflare.loader.php @@ -94,10 +94,8 @@ $cloudflarePurgeURLActions = array( 'deleted_post', // Delete a post - 'edit_post', // Edit a post - includes leaving comments 'delete_attachment', // Delete an attachment - includes re-uploading 'post_updated', // Update a post - 'comment_post', // Post a comment ); $cloudflarePurgeURLActions = apply_filters('cloudflare_purge_url_actions', $cloudflarePurgeURLActions); @@ -105,3 +103,9 @@ foreach ($cloudflarePurgeURLActions as $action) { add_action($action, array($cloudflareHooks, 'purgeCacheByRelevantURLs'), PHP_INT_MAX, 2); } + +/** + * Register two new actions which account for comment status before purging cache + */ +add_action('transition_comment_status', array($cloudflareHooks, 'purgeCacheOnCommentStatusChange'), PHP_INT_MAX, 3); +add_action('comment_post', array($cloudflareHooks, 'purgeCacheOnNewComment'), PHP_INT_MAX, 3); diff --git a/src/WordPress/Hooks.php b/src/WordPress/Hooks.php index 61621897..2af570c3 100644 --- a/src/WordPress/Hooks.php +++ b/src/WordPress/Hooks.php @@ -322,4 +322,33 @@ public function initAutomaticPlatformOptimization() header('cf-edge-cache: no-cache'); } } + + public function purgeCacheOnCommentStatusChange($new_status, $old_status, $comment) + { + if (!isset($comment->comment_post_ID) || empty($comment->comment_post_ID)) { + return; // nothing to do + } + + // in case the comment status changed, and either old or new status is "approved", we need to purge cache for the corresponding post + if (($old_status != $new_status) && (($old_status === 'approved') || ($new_status === 'approved'))) { + $this->purgeCacheByRelevantURLs($comment->comment_post_ID); + return; + } + } + + public function purgeCacheOnNewComment($comment_id, $comment_status, $comment_data) + { + if ($comment_status != 1) { + return; // if comment is not approved, stop + } + if (!is_array($comment_data)) { + return; // nothing to do + } + if (!array_key_exists('comment_post_ID', $comment_data)) { + return; // nothing to do + } + + // all clear, we ne need to purge cache related to this post id + $this->purgeCacheByRelevantURLs($comment_data['comment_post_ID']); + } }