I need get all comments of a post including of the meta value.. for eg. i need all comments fields + a meta value.

i tried the following code to get but.. its not working

$args = array( 
  'status' => 'approve', 
  'type' => 'comment', 
  'post_id' => '99', 
  'post_type' => 'product', 
  //'count' => true, 
  'meta_query' => array( 
      'key' => 'comment_rating_avg_key', 
      'compare' => 'EXISTS', 
$comments_query = new WP_Comment_Query; 
$comments = $comments_query->query( $args ); 

Do i need to write a custom query to get it ? or it can be done using default WP functions ?

  • 1
    "its not working" means what? Do you get results at all? Do you get the wrong results? What? – s_ha_dum Dec 20 '15 at 3:40
  • @s_ha_dum in the question i have mentioned that i need to get the comment along with the meta value. for which i have given in the code (Meta Query). i am getting the value for the comment. but not with the meta value – Varun Sridharan Dec 20 '15 at 3:58

WP_Comment_Query doesn't pull comment meta. You can search by comment meta but the query doesn't return that data. You could easily check this yourself by looking at the Codex.

You need to loop over the results and run get_comment_meta(), or essentially do the same via a filter on the_comments.

It is also possible to add to the data returned by filtering the "fields" clauses:

function add_cmeta_wpse_212423($clauses){
  //   var_dump($clauses);
  global $wpdb;
  $meta = "(SELECT meta_value
  FROM {$wpdb->commentmeta} 
    comment_id = comment_ID
    AND meta_key = 'test_comment_meta')
  ) as test_comment_meta";
  $clauses['fields'] .=  ', '.$meta;
  return $clauses;

I created a subquery. You could create a JOIN as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.