Subscribers to posts

If for “all the conversations a user is in” you mean “all the conversations where a user has commented” you dont need any additional table, just a SQL to get all the posts of conversation CPT where an user commented.

Here a function that should do the trick:

/**
 * Get posts (of a given CPT) an user has commented
 *
 * @param int|object|void $user User id or object to search. Void to use current user
 * @param string $cpt           Post type to get
 * @return array|bool           Posts array or FALSE if used bad arguments
 */
function get_user_conversations( $user = NULL, $cpt="conversation" ) {
  if ( empty( $user ) ) {
      $user = get_current_user_id();
  }
  if ( is_object( $user ) && isset( $user->ID ) ) {
    $user = $user->ID;
  }
  if ( ! is_numeric( $user ) || (int) $user <= 0 || ! post_type_exists( $cpt ) ) {
     return FALSE;
  }
  global $wpdb;
  $conv = $wpdb->get_results( $wpdb->prepare(
    "SELECT * FROM {$wpdb->posts} p
    INNER JOIN {$wpdb->comments} c ON p.ID = c.comment_post_ID
    WHERE p.post_type = %s 
    AND p.post_status="publish" AND c.user_id = %d
    GROUP BY p.ID ORDER BY p.post_date DESC",
    $cpt, $user
  ) );
  return empty( $conv ) ? array() : array_map( 'get_post', $conv );
}

Usage

You can use the function by passing to it as first argument:

  • an user ID, or
  • an use object, or
  • nothing (or any falsey value) in this case current user will be used

The second argument is the CPT slug, ‘conversation’ by default.

Examples:

/* via user id */
get_user_conversations( 1 );

/* via user object, and using a different post type slug */
$user = new WP_User( 1 );
get_user_conversations( $user, 'myapp_conversation' );

/* via current user */
get_user_conversations();

Returning values

Function can return:

  • array of WP_Post objects having conversation post type that given user has commented
  • an empty array, when given user has not commented any post
  • FALSE when a non existent user or a bad value or a non-registered post type is passed to function or when nothing is passed and there is no user currently logged in.

Gotchas

Of course, to make function works, you need to accept comments only by registered users, if you accept comments by non-logged visitors, than you can modify the function to look for user email, hoping your visitors always type the same email and always type it well.

Also note that function doesn’t take into account comment status, so even if an user has any not approved comments, the conversations where these comments are left, will be returned as well.

Suggested Improvements

Try to implement a sort of cache: do not run again the SQL query when it already ran. Of course, a comment by an user should invalidate the cache.