// you’re reading...

Open Source

Drupal Views: Hide or display alternate text for 0 (zero) comments

I have been playing with Drupal Views extensively for the last three months for a Website project. Whenever I overcome a hurdle with Views, I end up realizing how powerful and flexible is the Views module. It is just me who doesn’t know all the syntax to tap it’s power. Here is one such example. With about four lines of code, I was able to get rid of an annoyance in an otherwise neat-looking View.

For the Website project, I built a View to show the recent blog posts along with their title, author, post date and the number of comments. All looked fine expect the comments. It pinched me to see “0 comments”, in the View, against the posts, which did not have a comment. Ideally, the View should have  hidden the comments count or displayed an alternate text like “Write a comment”. Further, I didn’t want to theme the comment count for each individual View. This is because I had many such Views across the site. I desired a global fix to the “0 comment” case. The solution turned out to be quite simple and is as follows:

Save the following code in a file named views-view-field–comment-count.tpl.php in the theme’s directory –  <drupal-dir>/themes/<your-theme> . Please note the double hyphen (–) between “field” and “comment”, in the file name:

<?php

$zeroCommentText="0 comment(s)";

if(stristr($output,$zeroCommentText))
  $output="";

echo $output;

?>

The above code assumes that you have setup the View to display the comment count as “N comment(s)”. Here N is the number of comments. Change the $zeroCommentText variable to suit your display. The above code will not display the comment count when it is zero or no comments.

Following is the modified code, in case, you want to display some text, say, “Write a comment” in place of “0 comment(s)”:

<?php

$zeroCommentText="0 comment(s)";
$replaceWith = "Write a comment";   

if(stristr($output,$zeroCommentText))
  $output = str_ireplace($zeroCommentText,$replaceWith,$output);  

echo $output;

?>

Modify the $replaceWith variable, with the alternate text that you want to display for zero or no comments. Drupal Views rocks!!!

GD Star Rating
loading...
GD Star Rating
loading...
Drupal Views: Hide or display alternate text for 0 (zero) comments , 6.1 out of 10 based on 11 ratings
Share

Email This Post Email This Post Print This Post Print This Post Print This Post Post A Comment Tweet your comments/question to me @shekharg

Discussion

No comments for “Drupal Views: Hide or display alternate text for 0 (zero) comments”

Post a comment

Recent Tweets

Follow Me on Twitter