钩子文档

comments_number

💡 云策文档标注

概述

comments_number 是一个 WordPress 过滤器,用于修改评论数量显示文本。它允许开发者根据评论数量(0、1 或更多)自定义输出字符串,增强前端展示的灵活性。

关键要点

  • 过滤器名称:comments_number,通过 apply_filters 调用,用于过滤评论数量文本。
  • 参数:$comments_number_text(可翻译的字符串,基于评论数量格式化)和 $comments_number(评论数量整数)。
  • 用途:常用于主题或插件中,定制评论计数显示,如修改语言字符串或添加自定义样式。

代码示例

function wpdocs_comments_number_filter( $comments_number_text, $comments_number ) {
    if ( 0 === $comments_number ) {
        $comments_number_text = __( 'No Comments Yet' );
    } elseif ( 1 === $comments_number ) {
        $comments_number_text = __( 'One Comment' );
    } else {
        $comments_number_text = $comments_number . ' ' . __( 'Awesome Comments' );
    }

    return $comments_number_text;
}

add_filter( 'comments_number', 'wpdocs_comments_number_filter', 10, 2 );

注意事项

  • 确保在 add_filter 中正确设置优先级(如 10)和参数数量(如 2),以匹配过滤器回调函数。
  • 使用 __() 函数进行翻译,以支持多语言站点。
  • 此过滤器自 WordPress 1.5.0 版本引入,兼容性良好。

📄 原文内容

Filters the comments count for display.

Description

See also

Parameters

$comments_number_textstring
A translatable string formatted based on whether the count is equal to 0, 1, or 1+.
$comments_numberint
The number of post comments.

Source

return apply_filters( 'comments_number', $comments_number_text, $comments_number );

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    WordPress hooks provide a powerful way to modify and extend the core functionality of your site. The apply_filters function is used to apply filters to a variable, allowing you to modify data before it is used. The comments_number filter specifically allows you to alter the text that displays the number of comments before it is shown on the site.

    function wpdocs_comments_number_filter( $comments_number_text, $comments_number ) {
        if ( 0 === $comments_number ) {
            $comments_number_text = __( 'No Comments Yet' );
        } elseif ( 1 === $comments_number ) {
            $comments_number_text = __( 'One Comment' );
        } else {
            $comments_number_text = $comments_number . ' ' . __( 'Awesome Comments' );
        }
    
        return $comments_number_text;
    }
    
    add_filter( 'comments_number', 'wpdocs_comments_number_filter', 10, 2 );

    By using apply_filters with the comments_number filter, you can easily customize the comments number text in WordPress. This technique allows you to tailor the comments display to meet your specific needs.