Drupal Tip #4: Add "Views Count" column

It could be really interesting for your members to have an idea of how many times a subject has been viewed or read. Unfortunately, Drupal does not provide this in the default forum module, but it already provides some key features that helps integrating this views count really nicely and easily.

View Column Screenshot
The following article asserts that you already know well or understand how the hook and theme system of Drupal works. If not, you should consult the Drupal Theme and How to use the Theme layer in Drupal 6 documentation.
  1. Go to your Site Building, Modules menu and enable the Statistics module, if it is not already done. You don't need to download any additional package, as the Statistics module is bundled with the core package of Drupal. Note that if your forum exists since a long time and you've just enabled the Statistics module now, the view count will unfortunately start from now..
    Enable Statistics Module
  2. Then, once it is enabled, go to Administration, Reports and Access log settings, and check the Count content views option. Starting from this point, each time someone consults an existing node, a related counter will be incremented.

    Enable Count Content View
  3. Optional: You could also display this information in the links (generally at the bottom of a node) of a node by enabling the view post access counter rules in User Management, Permissions.

    Enable Statistics Permissions to display view count

Datas are now stored and automatically updated. This was the first and most important part. You now need to theme your existing Drupal theme.

Template Modifications

  1. First, modify your existing template.php file, and add the method below.

    Note: this template file is located in the folder of your current theme: themes/yourtheme/template.php, sites/yoursite/themes/yourtheme/template.php,...

    template.php

    function yourtheme_preprocess_forum_topic_list(&$variables) {
    	global $forum_topic_list_header;
     
    	$forum_topic_list_header = array(
    		array('data' => t('Topic'), 'field' => 'n.title'),
    		array('data' => t('Replies'), 'field' => 'l.comment_count'),
    		array('data' => t('Views')),
    		array('data' => t('Last Post'), 'field' => 'l.last_comment_timestamp'),
    	);
     
    	// Create the tablesorting header.
    	$ts = tablesort_init($forum_topic_list_header);
     
    	$header = '';
    	foreach ($forum_topic_list_header as $cell) {
    		$cell = tablesort_header($cell, $forum_topic_list_header, $ts);
    		$header .= _theme_table_cell($cell, TRUE);
    	}
    	$variables['header'] = $header;
     
    	foreach($variables["topics"] as $topic) {
    		$statistics = statistics_get($topic->nid);
    		if ($statistics == null) {
    			$total_count = 0;
    		}
    		else {
    			$total_count = $statistics["totalcount"];
    		}
     
    		// Not empty Last Post entry
    		if (trim($topic->last_reply) == "n/a") {
    			$topic->last_reply = $topic->created;
    		}			
     
    		$topic->views_count = $total_count;
    	}
     
    }

    Do not forget to replace yourtheme with the name of your theme. As you can see here, we did several things here:

    • First, we recreate the table header, and stores it to the $variables['header'].
    • Secondly, we created a new attribute, called views_count, that will store this value.
    • Third, we put the content of $topic->created in $topic->last_reply is this one is empty. It ensures to have an interesting data in the last column, that we renamed from "Last reply" to "Last Post". This is of course optional, and you can remove this code if you wish.

    Flush your cache every time you add a new hook function, else Drupal won't be able to detect new improvements.

  2. Then copy the following forum-topic-list.tpl.php file to the root of your theme folder. You can notice that we now use the $topic->views_count instead of the previous column.

    forum-topic-list.tpl.php

    <?php
    // $Id: forum-topic-list.tpl.php,v 1.4.2.1 2008/10/22 18:22:51 dries Exp $
     
    /**
     * @file forum-topic-list.tpl.php
     * Theme implementation to display a list of forum topics.
     *
     * Available variables:
     * - $header: The table header. This is pre-generated with click-sorting
     *   information. If you need to change this, @see template_preprocess_forum_topic_list().
     * - $pager: The pager to display beneath the table.
     * - $topics: An array of topics to be displayed.
     * - $topic_id: Numeric id for the current forum topic.
     *
     * Each $topic in $topics contains:
     * - $topic->icon: The icon to display.
     * - $topic->moved: A flag to indicate whether the topic has been moved to
     *   another forum.
     * - $topic->title: The title of the topic. Safe to output.
     * - $topic->message: If the topic has been moved, this contains an
     *   explanation and a link.
     * - $topic->zebra: 'even' or 'odd' string used for row class.
     * - $topic->num_comments: The number of replies on this topic.
     * - $topic->new_replies: A flag to indicate whether there are unread comments.
     * - $topic->new_url: If there are unread replies, this is a link to them.
     * - $topic->new_text: Text containing the translated, properly pluralized count.
     * - $topic->created: An outputtable string represented when the topic was posted.
     * - $topic->last_reply: An outputtable string representing when the topic was
     *   last replied to.
     * - $topic->timestamp: The raw timestamp this topic was posted.
     *
     * @see template_preprocess_forum_topic_list()
     * @see theme_forum_topic_list()
     */
    ?>
     
    <table id="forum-topic-<?php print $topic_id; ?>">
      <thead>
        <tr><?php print $header; ?></tr>
      </thead>
      <tbody>
      <?php
      	if (!$topics):
      ?>
      	<tr class="odd emptyTopic">
      	  <td colspan="5">
      	  	No existing topic.<br />
      	  	<?php
      	  		global $user;
      	 		if (!$user->uid):
      	  	?>
     	 		<a href="/user/login">Login</a> to create a new topic in forum.
     	 	<?php 
     	 		else:
     	 	?>
    	  	  	<a href="/node/add/forum/<?php print $topic_id; ?>">Create your topic now...</a>
      	  	<?php 
    		  	endif;
      	  	?>
      	  </td>
      	</tr>
      <?php 
      	endif;
      ?>
      <?php foreach ($topics as $topic): ?>
        <tr class="<?php print $topic->zebra;?>">
          <td class="title">
          	<div class="icon"><?php print $topic->icon; ?></div>
          	<?php print $topic->title; ?>
          	<div class="created"><?php print $topic->created; ?></div>
          </td>
        <?php if ($topic->moved): ?>
          <td colspan="3"><?php print $topic->message; ?></td>
        <?php else: ?>
          <td class="replies">
            <?php print $topic->num_comments; ?>
            <?php if ($topic->new_replies): ?>
              <br />
              <a href="<?php print $topic->new_url; ?>"><?php print $topic->new_text; ?></a>
            <?php endif; ?>
          </td>
          <td class="views"><?php print $topic->views_count; ?></td>
          <td class="last-reply"><?php print $topic->last_reply; ?></td>
        <?php endif; ?>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>

    As you can see here, this template file is really similar to the default one, instead that we use the new $topic->views_count variable.

  3. Finally, if you like our FSR theme, here is an CSS snippet that will help you to reproduce this style in your website.

    #forum table {
     width: 100%;
     border-collapse: separate;
     border-spacing: 0;
     border: 0;
    }
     
    #forum thead th {
     color: #fff;
     background: #505C65 url(images/forum-wrapper-bg.png) repeat-x 0 0;
     padding: 12px 0 4px;
     text-align: center;
     vertical-align: bottom;
     text-transform: uppercase;
     font-size: 10px;
     border: 0;
     
    }
     
    #forum thead th a {
     color: #fff;
    }
     
    #forum tr td.forum {
     background: transparent url(images/forum/forum-default.png) 6px 50% no-repeat;
     padding: 4px 0 4px 36px;
    }
     
    #forum .icon {
     width: 30px;
     float: left;
     margin: 4px 5px 0 5px;
    }
     
    #forum tbody tr td {
     border-bottom: 1px solid #D5DDF4;
     border-top: 1px solid #fff;
     border-left: 0;
     border-right: 0;
     padding: 4px
    }
     
    #forum tr.even td {
     background-color: #E8ECEE;
    }
     
    #forum tr.odd td {
     background-color: #E8ECEE;
    }
     
    #forum td.container {
     padding: 4px;
     background-color: #B8D6F0;
     color: #486e98;
    }
     
     
    #forum .container .name a {
     font-weight: bold;
     font-size: 15px;
    }
     
    #forum .name a {
     color: #105289;
    }
     
    #forum .description {
     color: #4C5D77;
    }
     
    #forum td.title a {
     color: #105289; 
    }
     
    #forum td.title .submitted-author, #forum td.title .submitted-time {
     font-size: 11px;
     padding-right: 5px;
    }
     
    #forum td.last-reply {
     padding : 2px;
     font-size: 11px;
     text-align: right;
     color: #4C5D77;
    }
     
    #forum td.last-reply .submitted-author, #forum td.last-reply .submitted-time {
     display: block;
    }
     
    #forum td.last-reply a, #forum td.created a {
     font-weight: normal;
    }
     
    #forum td.topics, #forum td.posts, #forum td.replies, #forum td.views {
     vertical-align: middle;
     font-size: 14px;
     text-align: center;
     color: #4C5D77;
     width: 60px;
    }
     
    #forum td.topics, #forum td.posts, #forum td.last-reply, #forum td.replies, #forum td.views {
     border-left: 1px solid #fff;
     margin: 4px; 
    }
     
    #forum td.topics a, #forum td.replies a {
     font-size: 11px; 
    }
     
    #forum table .created br {
     display: none;
    }

That's it, you now have a new useful Views column in your Drupal forum!

Complete displaying of the Views Column

See you soon for the next Drupal tip!

Keywords:
Comments are closed.

Comments (7)

Fantastic tutorial. Helped me

Fantastic tutorial. Helped me a lot. Just wanted to say thanks. Beer
A tiny improvement : specify where template.php is located.

Top
lastnico's picture

Thanks for your positive

Thanks for your positive comment.

I've added to the article the place where the template.php file is located.

FSR Admin - Vote for 2012.

Top

Great article. I loved it

Great article. I loved it and it helped a lot. Only question is, what if you want to see the topic author in the columns?

By the way, a small tip for any others that had this problem. When I did the above changes the forum column titles were all shifted to the left by one space. This is because I also have graphical icons for the folders from advanced forums. I just added an extra column called "status" in the array here.

$forum_topic_list_header = array(
                array('data' => t('Status')),
		array('data' => t('Topic'), 'field' => 'n.title'),
		array('data' => t('Replies'), 'field' => 'l.comment_count'),
		array('data' => t('Views')),
		array('data' => t('Last Post'), 'field' => 'l.last_comment_timestamp'),
	);

Top

Hi, there. first of all,

Hi, there. first of all, thanks very much for your such kind of great tutorial. that's great help; thanks very much; I did follow the tutorial from step by step; but finally I didn't get the view showing on my site? confusing.....still the same as the original; Would you give me help for this? thanks in advanced.
I installed advanced forum module and statistics module;
Puzzled

Top

sorry, i works fine. thanks,

sorry, i works fine. thanks, just by mistake of mine; thanks Cool

Top

hey there i've been lurking

hey there i've been lurking on the discussion boards and just wanted to chime in and make you aware that you are RSS feed wasn't working properly a sec ago.

Top
lastnico's picture

Is it working normally now?

Is it working normally now?

FSR Admin - Vote for 2012.

Top
  Top Top