1

I have a multilingual site, Comments in this site include a language field (field_language), so users who send comment to nodes must specify in what language they are sending the comment. On loading a node I want to display only the comments which their field_language is equal to the current website language. I tried this code based on the following result

enter image description here

function THEME_preprocess_node(&$variables) {
    global $language;
    foreach ($variables['content']['comments']['comments'] as $comment)
        if($comment['field_language']['#items'][0]['value'] != $language->language)
            unset($comment);
}

The $comment['field_language']['#items'][0]['value'] prints the comment field_language so I'm sure this is a correct syntax and the condition holds for a few comments but unset($comment); doesn't unset the comment.

I tried the following code

unset($variables['content']['comments']['comments'][71]);

and it successfully worked and removed the comment. The ID inside the [] is stored in the $comment['#entity_view_mode']['id'], I can easily use this ID to remove the comment but I think there must a more straightforward solution.

Is there any other solution like using hook_comment_load or anything else?

  • Interesting question and I will use this in the future. +1 :) – herci Aug 11 '15 at 8:10
  • 1
    @herci Andrew answer completes my solution but I'm still waiting for other solutions – M a m a D Aug 11 '15 at 9:48
2

This code should work for you

function THEME_preprocess_node(&$variables) {
  global $language;
  foreach ($variables['content']['comments']['comments'] as $key => $comment) {
    if ($comment['field_language']['#items'][0]['value'] != $language->language) {
      unset($variables['content']['comments']['comments'][$key]);
    }
  }     
}
| improve this answer | |
  • I don't like the [0] and ['value']. What if that changes? entity_metadata_wrappers could clean this up. but then again, this adds a dependency to entity. But when is this a problem? – Pinoniq Aug 11 '15 at 9:48
  • @Pinoniq I always use entity module. But here is a problem, I need to remove some comments based on the site language. My approach only removes the comments from the current page and it won't alter the Database, in fact it changes the way to display content. But when you use entity_metadata_wrappers you must use save() function which causes to completely remove that comment from the database. so it won't work in here. Besides that it only remains [0] because every comment has exactly one language field – M a m a D Aug 11 '15 at 9:57

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.