Like the title says: How can i prevent WordPress from deleting post comments when i delete a post?

What i am trying to accomplish is that i want to merge all comments from different posts to posts that are relative to eachother by posttitle or a predefined meta key in the post.
Sometimes i delete a post that is absolete and i still want those comments to show up for the undeleted posts.

I already have some of the comment aggregate coding for my functions.php. (still has to be adjusted a little bit for the query part to get results based on comment meta instead of the comment post id).

function multiple_comment_post_id_query_filter( $query )
{
    //todo:
    //get postid's from comments where a certain meta value is set. Database table wp_commentmeta
    //the meta value is extracted from the post meta value with the same id
    //when someone adds a comment, the comment meta will be included
    //put the captured post id's into an array with variable $post_ids 
    $post_ids = array ( 1, 2, 3, 4 );
    if ( FALSE === strpos( $query, 'comment_post_ID = ' ) )
    {
        return $query; // not the query we want to filter
    }

    remove_filter( 'query', 'multiple_comment_post_id_query_filter' );

    $replacement="comment_post_ID IN(" . implode( ',', $post_ids ) . ')';
    return preg_replace( '~comment_post_ID = \d+~', $replacement, $query );
}
add_filter( 'query', 'multiple_comment_post_id_query_filter' );

I prefer not to edit core files in case i have to upgrade (if there is no other possible way i will do it…)

1 Answer
1

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 Reply

Your email address will not be published. Required fields are marked *