0

Is there a way to delete pending WordPress comments after X days?

I looked into

do_action( 'wp_set_comment_status', $comment->comment_ID, 'delete' );

but now sure how to take it from here.

2
  • No, that would call the status change hook but not actually change the status - it's something WordPress does after changing the status to notify any interested code. Is it just deleting the comments you need help with, you've already got the scheduled jobs to find and delete old comments set up?
    – Rup
    Aug 21, 2022 at 16:07
  • No I didn't. I need the whole code if possible.
    – idomskt
    Aug 21, 2022 at 16:53

1 Answer 1

2

You have to create a schedule event.

It is a best practice to assign this schedule event to the activation of the plugin, and it should be cleared when the plugin is deactivated.

/**
 * Plugin activation
 * - create schedule event
 */
function enlsbv7_activation() {
    if ( ! wp_next_scheduled( 'enlsbv7_event' ) ) {
        wp_schedule_event( time(), 'daily', 'enlsbv7_event' );
    }
}

register_activation_hook( __FILE__, 'enlsbv7_activation' );

/**
 * Plugin deactivation
 * - clear schedule event
 */
function enlsbv7_deactivation() {
    wp_clear_scheduled_hook( 'enlsbv7_event' );
}

register_deactivation_hook( __FILE__, 'enlsbv7_deactivation' );

/**
 * Delete old pending comments
 */
function enlsbv7_event_delete_old_pending_comments() {

    $args = array(
        'date_query'     => array(
            'before' => '3 days ago',
        ),
        'posts_per_page' => - 1,
        'status'         => 'hold',
        'fields'         => 'ids',
        'no_found_rows'  => true,
    );

    $comment_ids = get_comments( $args );

    if ( ! empty( $comment_ids ) ) {
        foreach ( $comment_ids as $comment_id ) {
            wp_delete_comment( $comment_id, true );
        }
    }
}

add_action( 'enlsbv7_event', 'enlsbv7_event_delete_old_pending_comments' );

This will delete all pending comments older than 3 days. The schedule event runs daily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.