2

刚开始使用 PHP 的设计师正在寻找更优雅的解决方案

我正在尝试创建一个只有在帖子有评论时才会出现在帖子旁边的 div。我可以开始工作的唯一代码如下 & 那是通过创建两个变量,我觉得比我自己更有经验的人不需要,我只是无法用代码表达我在寻找什么。这是我使用 php 的第一周,所以我一直在谷歌搜索解决方案,只能找到使用 wordpress 函数 get_comments_number(); 生成评论数量的示例;& 然后用 javascript 隐藏 0 的 div,这对于如此琐碎的事情来说似乎过于复杂。

我喜欢有一些更像底部代码的东西,尤其是它输出单数和复数注释文本的方式,但我还不够胜任。

任何示例/建议将不胜感激

       <?php 
          $b = 0;
          $commBox = get_comments_number();

          if($commBox <=$b) {
                echo ""; 
          }else{
                echo "<div class=\"commentbox\"> $commBox </div>"; 
        }?>

     <?php if ( have_comments() ); ?>
     <div class="commentbox">
     <?php printf( _n( '1 comment;', '%1$s comments;', get_comments_number(), 'ves'),
     number_format_i18n( get_comments_number() ) ); ?>
     </div>
4

2 回答 2

2

您是否尝试过运行以下代码。如果帖子确实有评论,这只会创建一个 div,这意味着您不需要任何 JavaScript 来隐藏没有评论,因为它们不存在:

<?php 

if ( get_comments_number() > 0 ) {

echo '<div class="commentbox">';

comments_number( 'no comments', 'one comment', '% comments' );

echo '</div>';

}

?>

请注意该功能的使用,该comments_number()功能适用​​于您想要根据单个或多个评论显示不同的值。函数参考可以在这里找到。

于 2013-03-28T00:34:46.183 回答
1

清理顶部代码(我认为您要的是:

   <?php 
      $commBox = get_comments_number();
      if($commBox) {
            echo "<div class=\"commentbox\"> $commBox </div>"; 
    }
    ?>

这基本上只是检查 $commBox 是否为真(在 PHP 0 中为假,非零数字为真)并删除 uneccessary echo ""

您可以通过拥有一个返回 get_comments_number() 的函数来创建一个 have_comments() 函数,但我不确定这是否有必要。

编辑:类似于:

echo "<div class=\"commentbox\"> $commBox comment" . ($commBox == 1 ? 's' : '') . " </div>"; 

如果有超过 1 条评论,则应显示“评论”,如果有一条评论,则应显示“评论”(尽管这是未经测试的)。

于 2013-03-28T00:41:20.833 回答