在Comments.php模板中将注释计数为单数和复数

时间:2021-10-08 作者:Mary Hansen

我需要有关如何计算与文本格式相关的单个和多个注释的帮助。

Current output:讨论:1条评论和1条答案

Desired output:讨论:1条评论和1名回答者,当复数时-如上所述。

我一直在反复尝试,我被卡住了。

This is my code from my comments.php template:

<?php
$number_of_parents = comment_counter($post->ID);
$number_of_children = $post->comment_count - $number_of_parents;
?>
<?php if (have_comments()) : ?>
<h3 class="comments-title">Discussion: 
<?php if ($number_of_children > 0){
echo \'\'.$number_of_parents.\' questions and \'.$number_of_children.\' answers.\';
} else {
echo \'Questions: \'.$number_of_parents.\'\';
} ?></h3>

The function relates to this function, which I have in my functions.php file:

function comment_counter($id){
global $wpdb;
$query = "SELECT COUNT(comment_post_id) AS count FROM $wpdb->comments WHERE `comment_approved` = 1 AND `comment_post_ID` = $id AND `comment_parent` = 0";
$parents = $wpdb->get_row($query);
return $parents->count;
}

1 个回复
最合适的回答,由SO网友:Levi Cole 整理而成

这应该可以做到。。。

<?php
    $number_of_parents = comment_counter($post->ID);
    $number_of_children = $post->comment_count - $number_of_parents;
?>
<?php if ( have_comments() ): ?>
    <h3 class="comments-title">Discussion: 
        <?php if ( $number_of_children > 0 ): ?>
            <?php echo implode( \' \', [
                printf( _n( \'%d question\', \'%d questions\', $number_of_parents ), $number_of_parents ),
                __( \'and\' ),
                printf( _n( \'%d answer\', \'%d answers\', $number_of_children ), $number_of_parents )
            ] ); ?>
        <?php else:  ?>
            Questions: <?php echo $number_of_parents; ?>
        <?php endif ?>
    </h3>
<?php endif ?>