Can I store my custom comment_type into wp_comments table?

Comment type is similar to post type, because it allow to query only a specific type of comments, just like post type allow to query one or more post types.

And just like core post types (page, post) there are core comment type as well: 'comment', 'pingback', 'trackback'.

A difference between the two is that, by default, WP_Query do not fetch post types that are not explicilty required, but only the 'post' post type.

On the countrary, WP_Comment_Query, by default, fecth all comment types.

A lot of themes use wp_list_comments() to show comments.

That function has a 'type' argument that allow to set the comment type to show.

If you look at, for example, default themes, that function is used without the type argument. It means that, even if you use a custom comment type, that special comments will be shown among “regular” comments by most of the themes.

To overcome this issue you can use the 'pre_get_comments' hook to prevent your custom comment types to be fetched along “standard” comment types:

/* Assuming 'my_custom_comment_type' is the name of custom comment type */

add_action( 'pre_get_comments', function(\WP_Comment_Query $query) {
   /* only allow 'my_custom_comment_type' when is required explicitly */
   if ( $query->query_vars['type'] !== 'my_custom_comment_type' ) {
      $query->query_vars['type__not_in'] = array_merge(
          (array) $query->query_vars['type__not_in'],
          array('my_custom_comment_type')
      );
   }
});

Using code above, you can safely use 'my_custom_comment_type' to store comments that will be not mixed up with standard comments.

After that, when you need to fetch your custom comments, you need to explicitly pass the comment type slug, and everything should work fine.

However, note that functions normally used to retrieve comments, like wp_list_comments() or get_comments() automatically exclude comments that are not approved (or spam).

In fact, depending on your settings, if you use wp_new_comment() to store your custom comments, it is possible that they are stored as not approved and you will not able to fecth those comments even if explicitly using proper 'type' argument.

To avoid this, there are 3 possibilities:

  • always use the 'status' argument of WP_Comment_Query (or get_comments()) set to "all" when fetching custom comments type: this way all comments will be fecthed no matter if approved or not
  • use the more low-level wp_insert_comment() to save the comment, and set 'approved' argument to 1
  • use the filter ‘pre_comment_approved’ to always store as approved comments having your custom comment type:

    add_filter( 'pre_comment_approved', function( $approved, $data ) {
        return isset($data['comment_type']) && $data['comment_type'] === 'my_custom_comment_type'
           ? 1
           : $approved;
    }, 20, 2);
    

Leave a Comment