Deleting the attached “comment replies” when trashing a comment

When sending a comment to the bin, the attached “comment replies” does not get trashed or deleted.

How can you configure wordpress so that when you trash a comment, the comment replies automatically gets deleted?

Related posts

1 comment

  1. You could build an action for delete_comment, where you loop through the childcomments and delete them.

    I use two different functions here, one that trashes the childcomments (hooked into trash_comment), and one that deletes them directly.

    Please make sure which funtion you use, or if you want to use both. The safe version would be to move the childcomments to trash, not delete them in the first place – in this case you have to hook f711_trash_child_comments to delete_comment.

    Please be aware that this function is fully recursive. The actions get called before the comment is actually deleted, so in a timeline the nested comments get deleted first, from the bottom level up.

    add_action( 'delete_comment', 'f711_delete_child_comments' ); // complete deletion
    add_action( 'trash_comment', 'f711_trash_child_comments' ); // move to trash
    
    
    function f711_delete_child_comments( $comment_id ) {
    
        global $wpdb;
        $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) ); //select the comments where the parentcomment is the comment to be deleted
    
        if ( !empty($children) ) {
            foreach( $children as $thischild => $childid ) {
    
                wp_delete_comment( $childid, true ); // set second parameter to false if you just want to move it to the trash
    
            }
    
        }
    
    }
    
    function f711_trash_child_comments( $comment_id ) {
    
        global $wpdb;
        $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) ); //select the comments where the parentcomment is the comment to be deleted
    
        if ( !empty($children) ) {
            foreach( $children as $thischild => $childid ) {
    
                wp_trash_comment( $childid ); // set second parameter to false if you just want to move it to the trash
    
            }
    
        }
    
    }
    

Comments are closed.