使用 Anchor CMS 在 posts.php 页面上显示“0 条评论”文本

Show '0 comments' text on posts.php page using Anchor CMS

我正在使用这个 PHP 在我的主页上显示评论:

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>';
 }

?>

一切正常,但当 post 有 0 条评论时,根本不显示任何文本,而我希望它显示“0 条评论”。我对 PHP 有点外行,所以这里有什么我需要修改的地方吗?

您首先检查评论数是否大于 0,但如果评论数等于 0,则什么都不做。

你需要一个 else 来第一次检查评论,即

<?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 添加了括号以提高可读性并使逻辑更清晰,如果您愿意,可以随意删除。