Skip to content

Instantly share code, notes, and snippets.

@palicko
Last active December 9, 2019 11:07
Show Gist options
  • Save palicko/b97eab7903458df97cca618a5956be02 to your computer and use it in GitHub Desktop.
Save palicko/b97eab7903458df97cca618a5956be02 to your computer and use it in GitHub Desktop.
Remove all comments and fix out of sync comments count SQL. Works also with WC reviews.
# Remove all comments
TRUNCATE `wp_commentmeta`;
TRUNCATE `wp_comments`
# We also need to remove comments counts, which are set in postmeta table
# Get count which are out of sync
SELECT wpp.id, wpp.post_title, wpp.comment_count, wpc.cnt
FROM wp_posts wpp
LEFT JOIN
(SELECT comment_post_id AS c_post_id, count(*) AS cnt FROM wp_comments
WHERE comment_approved = 1 GROUP BY comment_post_id) wpc
ON wpp.id=wpc.c_post_id
WHERE wpp.post_type IN ('post', 'page', 'product')
AND (wpp.comment_count!=wpc.cnt OR (wpp.comment_count != 0 AND wpc.cnt IS NULL));
# Set all out of sync comment counts to 0 (this doesn't work for WC products)
UPDATE wp_posts wpp
LEFT JOIN
(SELECT comment_post_id AS c_post_id, count(*) AS cnt FROM wp_comments
WHERE comment_approved = 1 GROUP BY comment_post_id) wpc
ON wpp.id=wpc.c_post_id
SET wpp.comment_count=0
WHERE wpp.post_type IN ('post', 'page', 'product')
AND (wpp.comment_count!=wpc.cnt OR (wpp.comment_count != 0 AND wpc.cnt IS NULL));
# Get all meta values for product reviews count/ratings
SELECT wpmt.meta_id, wpmt.post_id, wpmt.meta_value
FROM wp_postmeta wpmt
WHERE (meta_key = '_wc_rating_count' OR meta_key = '_wc_review_count' OR meta_key = '_wc_average_rating');
# Set all product reviews count/ratings to 0
UPDATE wp_postmeta
SET meta_value=0
WHERE (meta_key = '_wc_rating_count' OR meta_key = '_wc_review_count' OR meta_key = '_wc_average_rating');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment