get_next_comments_link()
云策文档标注
概述
get_next_comments_link() 函数用于生成指向下一评论页的 HTML 链接,适用于单篇文章的评论分页场景。它检查当前页面状态,计算下一页链接,并支持自定义标签和属性过滤。
关键要点
- 函数返回下一评论页的 HTML 格式链接,若不存在则返回空。
- 参数包括可选的标签文本 $label、最大页数 $max_page 和当前页码 $page,默认值分别为空字符串、0 和 null。
- 仅在单篇文章页面(is_singular() 为 true)时有效,否则直接返回。
- 使用 get_query_var('cpage') 获取当前评论页码,并计算下一页。
- 通过 next_comments_link_attributes 过滤器允许自定义链接的锚点属性。
- 相关函数包括 get_comments_pagenum_link()、get_comment_pages_count() 等,用于链接生成和页数计算。
代码示例
function get_next_comments_link( $label = '', $max_page = 0, $page = null ) {
global $wp_query;
if ( ! is_singular() ) {
return;
}
if ( is_null( $page ) ) {
$page = get_query_var( 'cpage' );
}
if ( ! $page ) {
$page = 1;
}
$next_page = (int) $page + 1;
if ( empty( $max_page ) ) {
$max_page = $wp_query->max_num_comment_pages;
}
if ( empty( $max_page ) ) {
$max_page = get_comment_pages_count();
}
if ( $next_page > $max_page ) {
return;
}
if ( empty( $label ) ) {
$label = __( 'Newer Comments »' );
}
$attr = apply_filters( 'next_comments_link_attributes', '' );
return sprintf(
'%3$s',
esc_url( get_comments_pagenum_link( $next_page, $max_page ) ),
$attr,
preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&$1', $label )
);
}注意事项
- 确保在单篇文章上下文中调用此函数,否则可能无法正确生成链接。
- 使用 next_comments_link_attributes 过滤器可以添加自定义 CSS 类或其他 HTML 属性到链接标签。
- 函数自 WordPress 2.7.1 引入,6.7.0 版本增加了 $page 参数,便于更灵活地控制页码。
原文内容
Retrieves the link to the next comments page.
Parameters
$labelstringoptional-
Label for link text. Default empty.
$max_pageintoptional-
Max page. Default 0.
$pageint|nulloptional-
Page number.
Default:
null
Source
function get_next_comments_link( $label = '', $max_page = 0, $page = null ) {
global $wp_query;
if ( ! is_singular() ) {
return;
}
if ( is_null( $page ) ) {
$page = get_query_var( 'cpage' );
}
if ( ! $page ) {
$page = 1;
}
$next_page = (int) $page + 1;
if ( empty( $max_page ) ) {
$max_page = $wp_query->max_num_comment_pages;
}
if ( empty( $max_page ) ) {
$max_page = get_comment_pages_count();
}
if ( $next_page > $max_page ) {
return;
}
if ( empty( $label ) ) {
$label = __( 'Newer Comments »' );
}
/**
* Filters the anchor tag attributes for the next comments page link.
*
* @since 2.7.0
*
* @param string $attributes Attributes for the anchor tag.
*/
$attr = apply_filters( 'next_comments_link_attributes', '' );
return sprintf(
'<a href="%1$s" %2$s>%3$s</a>',
esc_url( get_comments_pagenum_link( $next_page, $max_page ) ),
$attr,
preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&$1', $label )
);
}
Hooks
- apply_filters( ‘next_comments_link_attributes’, string $attributes )
-
Filters the anchor tag attributes for the next comments page link.