Wrap comments in a collapsible fieldset

Estimated reading time of this article: 1 minute 9 seconds

Do you want to wrap comments in a collapsible fieldset in Drupal 7?

Add the following function to your template.php of your theme:

<?php
/**
 * Wraps comments in a collapsible fieldset.
 */
function YOUR_THEME_preprocess_comment_wrapper(&$variables) {
 
// Provide contextual information.
 
$variables['node'] = $variables['content']['#node'];
 
$variables['display_mode'] = variable_get('comment_default_mode_' . $variables['node']->type, COMMENT_MODE_THREADED);
 
// The comment form is optional and may not exist.
 
$variables['content'] += array('comment_form' => array());
 
$commentslist = $variables['content']['comments'];
 
$variables['content']['comments'] = array(
   
'#type' => 'fieldset',
   
'#title' => format_plural($variables['node']->comment_count, '1 comment', '@count comments'),
   
'#weight' => 0,
   
//'#collapsible' => TRUE, // does not work and thus is not necessary
    //'#collapsed' => TRUE, // does not work and thus is not necessary
   
'#pre_render' => array(),
   
'#attributes' => array(),
  );
 
// Make it manually collapsible as we cannot use #collapsible without the
  // FAPI element processor.
 
$variables['content']['comments']['#attached']['library'][] = array('system', 'drupal.collapse');
 
$variables['content']['comments']['#attributes']['class'][] = 'collapsible';
 
$variables['content']['comments']['#attributes']['class'][] = 'collapsed';
 
$variables['content']['comments']['commentslist'] = $commentslist;
}
?>