最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - get_comments_number() returns 0

programmeradmin2浏览0评论

I am customizing a theme that has the following code to display comments:

if ( have_comments() ) : ?>
    <h2 class="comments-title">
        <?php
            printf( // WPCS: XSS OK.
                esc_html( _nx( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', get_comments_number(), 'comments title', 'kadabra' ) ),
                number_format_i18n( get_comments_number() ),
                '<span>' . get_the_title() . '</span>'
            );
        ?>
    </h2>

however it always shows the following:

0 thoughts on “Post title”

even though I have several comments and the if ( have_comments() ) : part is passed. Any ideas?

PS: wp_debug is enabled and show no errors as well.

I am customizing a theme that has the following code to display comments:

if ( have_comments() ) : ?>
    <h2 class="comments-title">
        <?php
            printf( // WPCS: XSS OK.
                esc_html( _nx( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', get_comments_number(), 'comments title', 'kadabra' ) ),
                number_format_i18n( get_comments_number() ),
                '<span>' . get_the_title() . '</span>'
            );
        ?>
    </h2>

however it always shows the following:

0 thoughts on “Post title”

even though I have several comments and the if ( have_comments() ) : part is passed. Any ideas?

PS: wp_debug is enabled and show no errors as well.

Share Improve this question asked Jul 3, 2017 at 16:27 Deka87Deka87 1319 bronze badges 2
  • try get_comments_number($post) maybe? although if have_comments and get_the_title are both working without a post object/id in them then that should as well. do you still get 0 if you var_dump comments_number? – mrben522 Commented Jul 3, 2017 at 17:22
  • Are you running the code inside The Loop? – cybmeta Commented Jul 3, 2017 at 18:42
Add a comment  | 

2 Answers 2

Reset to default 1

From quick look at the source there seems to be three possibilities:

  1. get_post() returned falsy value, so current post context is invalid in some way.
  2. $post->comment_count is 0.
  3. get_comments_number filter is being used to adjust the output.

Most commonly it would be case 1/2 with something interfering with global post context, dump get_post() at the point and see if it contains expected instance.

What probably happened is that you did not approve comments in admin panel.

When you only have comments that are "pending" you still pass have_comments(), but those comments are not counted.

发布评论

评论列表(0)

  1. 暂无评论