1

I know how to programmatically delete comments that are X days old but they then go to the trash. How do I empty the comment trash every X days?

function md_scheduled_delete_commentsmd_scheduled_delete_comments() {
    $comments = get_comments( array(
        'post_type' => 'post',
        'date_query' => array(
            'before' => '3 days ago',
        ),
    ) );

    if ( $comments ) {
        foreach ( $comments as $comment ) {
            wp_delete_comment( $comment );
        }
    }
}
add_action( 'wp_scheduled_delete', 'md_scheduled_delete_comments' );
// You can test it immediately by adding following line:
// add_action( 'wp_loaded', 'md_scheduled_delete_comments' );
1

When deleting a comment it's possible to use the second input argument:

wp_delete_comment( $comment, $force_delete = true ) 

to delete it permanently and avoiding the trash bin. You could try to adjust your scheduled script accordingly.

There's also the EMPTY_TRASH_DAYS constant, that's default set to empty the trash bin after 30 days, but it will affect comments, posts, pages and other post types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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