Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delete spam comments from every site on a WordPress network, slowly but surely
<?php
function qw_delete_spam_comments() {
$in_progress = (bool) get_site_option( 'qw_delete_in_progress' );
if ( ! $in_progress ) {
global $wpdb;
update_site_option( 'qw_delete_in_progress', '1' );
// 4980
$next = (int) get_site_option( 'qw_delete_next_blog' );
if ( empty( $next ) ) {
$next = 1;
}
if ( $next > 4980 ) {
return;
}
switch_to_blog( $next );
$spams = $wpdb->get_col( "SELECT comment_id FROM {$wpdb->comments} WHERE comment_approved = 'spam' LIMIT 10" );
if ( empty( $spams ) ) {
$next++;
update_site_option( 'qw_delete_next_blog', $next );
} else {
foreach ( $spams as $spam ) {
wp_delete_comment( $spam, true );
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->commentmeta} WHERE comment_id = %d", $spam ) );
}
}
// reclaim disk space
$wpdb->query( "OPTIMIZE TABLE {$wpdb->comments}" );
$wpdb->query( "OPTIMIZE TABLE {$wpdb->commentmeta}" );
restore_current_blog();
delete_site_option( 'qw_delete_in_progress' );
}
}
register_shutdown_function( 'qw_delete_spam_comments' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment