How to prevent deleting of comments when deleting a post

To prevent the comment deletion hook into before_delete_post, and filter the query for associated comments so the deletion routine cannot find and delete those.

PHP 5.3 required:

add_action( 'before_delete_post', function( $post_id ) {
    add_filter( 'query', function( $query ) use ( $post_id ) {
        $find = 'WHERE comment_parent=";
        FALSE !== strpos( $query, $find . $post_id )
            and $query = str_replace( $find . $post_id, $find . "-1', $query );

        return $query;
    });
});

Here is a noisy old-school version:

add_action(
    'before_delete_post',
    array ( 'T5_Prevent_Comment_Deletion', 'start' )
);

class T5_Prevent_Comment_Deletion
{
    protected static $post_id = 0;

    public static function start( $post_id )
    {
        self::$post_id = $post_id;
        add_filter( 'query', array ( __CLASS__, 'hide_comments' ) );
    }

    public function hide_comments( $query )
    {
        $find = 'WHERE comment_parent=" . self::$post_id;

        if ( FALSE !== strpos( $query, $find ) )
        {
            $query = str_replace( $find, "WHERE comment_parent = -1', $query );
            remove_filter( 'query', array ( __CLASS__, 'hide_comments' ) );
        }

        return $query;
    }
}

Leave a Comment