get_previous_comments_link()
云策文档标注
概述
get_previous_comments_link() 函数用于检索上一页评论的链接,适用于单篇文章页面。它接受可选参数控制标签和页码,并返回 HTML 格式的链接。
关键要点
- 函数返回上一页评论的 HTML 链接,若不在单篇文章页面则返回 void。
- 参数 $label 可选,用于设置链接文本标签,默认为空字符串。
- 参数 $page 可选,指定页码,默认为 null,自动从查询变量获取。
- 内部使用 get_comments_pagenum_link() 生成链接,并应用过滤器 previous_comments_link_attributes。
- 相关函数包括 is_singular()、get_query_var() 和 previous_comments_link()。
代码示例
function get_previous_comments_link( $label = '', $page = null ) {
if ( ! is_singular() ) {
return;
}
if ( is_null( $page ) ) {
$page = get_query_var( 'cpage' );
}
if ( (int) $page <= 1 ) {
return;
}
$previous_page = (int) $page - 1;
if ( empty( $label ) ) {
$label = __( 'Older Comments' );
}
$attr = apply_filters( 'previous_comments_link_attributes', '' );
return sprintf(
'<a href="%1$s" %2$s>%3$s</a>',
esc_url( get_comments_pagenum_link( $previous_page ) ),
$attr,
preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&$1', $label )
);
}注意事项
- 此函数仅在单篇文章页面有效,否则无输出。
- 版本 6.7.0 新增了 page 参数,增强灵活性。
- 链接文本可通过 $label 参数自定义,支持国际化。
原文内容
Retrieves the link to the previous comments page.
Parameters
$labelstringoptional-
Label for comments link text. Default empty.
$pageint|nulloptional-
Page number.
Default:
null
Source
function get_previous_comments_link( $label = '', $page = null ) {
if ( ! is_singular() ) {
return;
}
if ( is_null( $page ) ) {
$page = get_query_var( 'cpage' );
}
if ( (int) $page <= 1 ) {
return;
}
$previous_page = (int) $page - 1;
if ( empty( $label ) ) {
$label = __( '« Older Comments' );
}
/**
* Filters the anchor tag attributes for the previous comments page link.
*
* @since 2.7.0
*
* @param string $attributes Attributes for the anchor tag.
*/
$attr = apply_filters( 'previous_comments_link_attributes', '' );
return sprintf(
'<a href="%1$s" %2$s>%3$s</a>',
esc_url( get_comments_pagenum_link( $previous_page ) ),
$attr,
preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&$1', $label )
);
}
Hooks
- apply_filters( ‘previous_comments_link_attributes’, string $attributes )
-
Filters the anchor tag attributes for the previous comments page link.