0

I'm using this PHP to show the comments on my homepage:

Functions.php

function tootsweet_article_total_comments() {
return Comment::where('post', '=', article_id())
      ->where('status', '=', 'approved')
      ->count();
 }

Posts.php

<?php if (tootsweet_article_total_comments() > 0) 
 {
   echo '<a href="'.article_url().'#comments">';
   if (tootsweet_article_total_comments() == 1) 
     echo ' comment';
   else
    echo tootsweet_article_total_comments().' comments';
   echo '</a>';
 }

?>

All is working perfectly, but when a post has 0 comments, no text is shown at all whereas I want it to say '0 comments'. I'm a bit of an amateur with PHP, so is there something I need to amend here?

Laurel
  • 5,965
  • 14
  • 31
  • 57
Kaye Huett
  • 61
  • 9

1 Answers1

1

You start by checking if the number of comments is greater then 0, but you don't do anything if the number of comments is equal to 0.

You'd need an else to your first check for comments, i.e.

<?php 
if (tootsweet_article_total_comments() > 0) {
    echo '<a href="'.article_url().'#comments">';

    if (tootsweet_article_total_comments() == 1) {
        echo ' comment</a>';
    } else {
        echo tootsweet_article_total_comments().' comments';
        echo '</a>';
    }
} else {
    echo "<a href='" . article_url() . "'>0 comments</a>";
}    
?>

n.b added brackets for readability and to make the logic clearer, feel free to remove if you prefer.

atmd
  • 7,430
  • 2
  • 33
  • 64
  • Brilliant, thanks. How do I make the '0 comments' a link, the same as if there are plural comments? – Kaye Huett Jan 29 '15 at 08:43
  • I've just noticed there's an issue when a post only has 1 comment. It causes all of the text in the post to become a link, as if the opening link for 'Comment' isn't closed? – Kaye Huett Jan 30 '15 at 21:34
  • That's because the closing ` echo '';` is in the `else` statement. have updated the answer – atmd Feb 02 '15 at 08:29