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…)
To prevent the comment deletion hook into
before_delete_post
, and filter thequery
for associated comments so the deletion routine cannot find and delete those.PHP 5.3 required:
Here is a noisy old-school version: