Looping through WordPress Comments Programmatically and comparing their Meta

Recently I was importing comments and reviews from one CMS to a WordPress CMS. I couldn't find a way to loop through comments fields with Pods unfortunately, as the comments themselves weren't extended yet with Pods.

But that doesn't mean we can't cycle through them in the good old-fashioned WordPress way :

In this example I wanted to check if a comment I'm about to import, already existed in the database ( and in that case ignore it ). For that reason every imported comments gets a meta field _orig_id attached to it, and later on we check if a comment with such a value already exists on this post.

Here's our little helper import_comment_exists($post_id, $orig_id)

function check_if_comment_exists($post_id, $orig_id) {
  $comment_array = get_approved_comments($post_id);
  foreach($comment_array as $comment){
    if(get_comment_meta($comment->comment_ID, '_orig_id', true) == $orig_id) {
      return true;
    }
  }
  return false;
}

It's not a performant function, as we're looping through all approved comments for that post, however when importing data sets – performance shouldn't be a big issue.