get_comments_pagenum_link()
云策文档标注
概述
get_comments_pagenum_link() 函数用于生成评论分页链接的 URL,根据评论分页设置和参数动态构建链接。
关键要点
- 函数返回评论分页链接的字符串 URL,支持默认评论页面设置(如 'newest')和分页参数。
- 参数包括 $pagenum(页码,默认 1)和 $max_page(最大评论页数,默认 0),均转换为整数处理。
- 根据 WP_Rewrite 是否使用固定链接,使用不同方式构建 URL(如 user_trailingslashit 或 add_query_arg)。
- 链接末尾自动添加 '#comments' 锚点,便于跳转到评论区域。
- 通过 apply_filters('get_comments_pagenum_link', $result) 提供钩子,允许开发者过滤链接。
代码示例
function get_comments_pagenum_link( $pagenum = 1, $max_page = 0 ) {
global $wp_rewrite;
$pagenum = (int) $pagenum;
$max_page = (int) $max_page;
$result = get_permalink();
if ( 'newest' === get_option( 'default_comments_page' ) ) {
if ( $pagenum !== $max_page ) {
if ( $wp_rewrite->using_permalinks() ) {
$result = user_trailingslashit( trailingslashit( $result ) . $wp_rewrite->comments_pagination_base . '-' . $pagenum, 'commentpaged' );
} else {
$result = add_query_arg( 'cpage', $pagenum, $result );
}
}
} elseif ( $pagenum > 1 ) {
if ( $wp_rewrite->using_permalinks() ) {
$result = user_trailingslashit( trailingslashit( $result ) . $wp_rewrite->comments_pagination_base . '-' . $pagenum, 'commentpaged' );
} else {
$result = add_query_arg( 'cpage', $pagenum, $result );
}
}
$result .= '#comments';
return apply_filters( 'get_comments_pagenum_link', $result );
}注意事项
- 函数内部依赖全局变量 $wp_rewrite 和多个辅助函数(如 get_permalink、get_option),确保这些组件正常工作。
- 钩子 apply_filters('get_comments_pagenum_link', $result) 允许自定义链接输出,使用时需注意参数类型。
- 自 WordPress 2.7.0 版本引入,兼容性良好,但建议在开发时检查相关函数和选项的可用性。
原文内容
Retrieves the comments page number link.
Parameters
$pagenumintoptional-
Page number.
Default:
1 $max_pageintoptional-
The maximum number of comment pages. Default 0.
Source
function get_comments_pagenum_link( $pagenum = 1, $max_page = 0 ) {
global $wp_rewrite;
$pagenum = (int) $pagenum;
$max_page = (int) $max_page;
$result = get_permalink();
if ( 'newest' === get_option( 'default_comments_page' ) ) {
if ( $pagenum !== $max_page ) {
if ( $wp_rewrite->using_permalinks() ) {
$result = user_trailingslashit( trailingslashit( $result ) . $wp_rewrite->comments_pagination_base . '-' . $pagenum, 'commentpaged' );
} else {
$result = add_query_arg( 'cpage', $pagenum, $result );
}
}
} elseif ( $pagenum > 1 ) {
if ( $wp_rewrite->using_permalinks() ) {
$result = user_trailingslashit( trailingslashit( $result ) . $wp_rewrite->comments_pagination_base . '-' . $pagenum, 'commentpaged' );
} else {
$result = add_query_arg( 'cpage', $pagenum, $result );
}
}
$result .= '#comments';
/**
* Filters the comments page number link for the current request.
*
* @since 2.7.0
*
* @param string $result The comments page number link.
*/
return apply_filters( 'get_comments_pagenum_link', $result );
}
Hooks
- apply_filters( ‘get_comments_pagenum_link’, string $result )
-
Filters the comments page number link for the current request.
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |