Skip to content

Commit

Permalink
Merge pull request #356 from softmanro/master
Browse files Browse the repository at this point in the history
Change purge logic for comments
  • Loading branch information
jacobbednarz authored Feb 22, 2021
2 parents f4c6740 + e0447c9 commit d8445a4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
8 changes: 6 additions & 2 deletions cloudflare.loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,18 @@

$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);

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);
29 changes: 29 additions & 0 deletions src/WordPress/Hooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
}
}

0 comments on commit d8445a4

Please sign in to comment.