get_previous_posts_link()
云策文档标注
概述
get_previous_posts_link() 函数用于检索上一页文章链接的 HTML 格式字符串。它基于当前分页状态和可选标签参数生成链接,适用于非单篇文章页面且分页大于1的情况。
关键要点
- 函数返回 HTML 格式的上一页链接字符串,或 void(无返回值)。
- 参数 $label 可选,用于自定义链接文本,默认值为 null(自动使用翻译后的“« Previous Page”)。
- 仅在非单篇文章页面(is_single() 为 false)且当前分页 $paged 大于1时生成链接。
- 通过 previous_posts_link_attributes 过滤器可修改锚点标签的属性。
- 函数内部使用 previous_posts() 获取链接 URL,并处理标签文本的 HTML 实体。
代码示例
// 默认用法,输出上一页链接
echo get_previous_posts_link();
// 自定义标签文本
echo get_previous_posts_link( 'Go Back' );注意事项
- 确保在正确的上下文中调用,例如在文章列表分页导航中。
- 如果使用无尾部斜杠的 URL,可通过 previous_posts_link_attributes 过滤器移除生成链接中的尾部斜杠。
原文内容
Retrieves the previous posts page link.
Parameters
$labelstringoptional-
Previous page link text.
Default:
null
Source
function get_previous_posts_link( $label = null ) {
global $paged;
if ( null === $label ) {
$label = __( '« Previous Page' );
}
if ( ! is_single() && $paged > 1 ) {
/**
* Filters the anchor tag attributes for the previous posts page link.
*
* @since 2.7.0
*
* @param string $attributes Attributes for the anchor tag.
*/
$attr = apply_filters( 'previous_posts_link_attributes', '' );
return sprintf(
'<a href="%1$s" %2$s>%3$s</a>',
previous_posts( false ),
$attr,
preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&$1', $label )
);
}
}
Hooks
- apply_filters( ‘previous_posts_link_attributes’, string $attributes )
-
Filters the anchor tag attributes for the previous posts page link.
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |
Skip to note 3 content
Codex
Default Usage
echo get_previous_posts_link();Skip to note 4 content
Akira Tachibana
[From Codex] Removing Trailing Slashes from Prev & Next links
If you are using no-end-trailing slashes for your URLs. You may add following filter in your functions file to remove trailing slashes from generated links from
get_previous_posts_links()function.