get_year_link()
云策文档标注
概述
get_year_link() 函数用于获取指定年份归档页面的固定链接。它支持自定义年份参数,并处理不同重写规则下的链接生成。
关键要点
- 函数接受一个整数参数 $year,表示年份;若为 false 则使用当前年份。
- 返回值为字符串类型的归档页面永久链接。
- 内部逻辑基于 WP_Rewrite 类:优先使用重写结构生成链接,否则回退到查询字符串格式。
- 通过 apply_filters('year_link', $yearlink, $year) 钩子允许过滤链接输出。
- 相关函数包括 current_time()、user_trailingslashit()、WP_Rewrite::get_year_permastruct() 和 home_url()。
代码示例
// 获取当前年份归档链接
$current_year_link = get_year_link( false );
// 获取指定年份(如2003)归档链接
$year2003_link = get_year_link( 2003 );
// 在模板中输出链接
echo '<a href="' . esc_url( get_year_link( 2003 ) ) . '">Posts from 2003</a>';注意事项
- 确保重写规则已正确设置,否则链接可能回退到查询字符串格式(如 ?m=2023)。
- 使用 apply_filters('year_link') 可自定义链接生成逻辑。
- 函数自 WordPress 1.5.0 版本引入,兼容性良好。
原文内容
Retrieves the permalink for the year archives.
Parameters
$yearint|falserequired-
Integer of year. False for current year.
Source
function get_year_link( $year ) {
global $wp_rewrite;
if ( ! $year ) {
$year = current_time( 'Y' );
}
$yearlink = $wp_rewrite->get_year_permastruct();
if ( ! empty( $yearlink ) ) {
$yearlink = str_replace( '%year%', $year, $yearlink );
$yearlink = home_url( user_trailingslashit( $yearlink, 'year' ) );
} else {
$yearlink = home_url( '?m=' . $year );
}
/**
* Filters the year archive permalink.
*
* @since 1.5.0
*
* @param string $yearlink Permalink for the year archive.
* @param int $year Year for the archive.
*/
return apply_filters( 'year_link', $yearlink, $year );
}
Hooks
- apply_filters( ‘year_link’, string $yearlink, int $year )
-
Filters the year archive permalink.
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 4 content
Codex
Year as Link
Returns the URL for the current year’s archive, displaying it as a link in the anchor tag by using the PHP echo command.
<a href="<?php echo get_year_link(''); ?>">Posts from this year</a>Skip to note 5 content
Codex
Year as a variable
Returns URL for the archive year 2003, assigning it to the variable $year03. The variable can then be used elsewhere in a page.
Skip to note 6 content
Codex
Using With PHP Variables
PHP code block for use within The Loop: Assigns year to the variable $arc_year. This is used with the get_year_link() tag, which returns the URL as a link to the yearly archive for a post, displaying it within an anchor tag with the PHP echo command. See Formatting Date and Time for info on format strings used in get_the_time() tag.
<a href="<?php echo get_year_link( $archive_year ); ?>"> archive</a>