single_month_title()
云策文档标注
概述
single_month_title() 函数用于在日期归档页面显示或检索基于月份和年份的页面标题。它适用于模板中仅需展示月份和年份的场景,但需注意前缀参数不会自动添加空格。
关键要点
- 函数功能:显示或检索基于日期的归档页面标题,仅当月份和年份可用时生效。
- 参数说明:$prefix 参数用于设置标题前缀,需手动添加空格;$display 参数控制是否直接输出或返回标题,默认值为 true。
- 返回值:若无有效标题则返回 false;检索时返回标题字符串。
- 使用限制:仅当 WordPress 传递了 m 或 archive month 参数到当前页面时有效,即仅适用于月度归档页面,不适用于分类模板等。
- 注意事项:前缀不会自动添加空格,需在参数值中手动设置;不支持在标题后添加分隔符,但可通过空前缀手动设置。
代码示例
function single_month_title( $prefix = '', $display = true ) {
global $wp_locale;
$m = get_query_var( 'm' );
$year = get_query_var( 'year' );
$monthnum = get_query_var( 'monthnum' );
if ( ! empty( $monthnum ) && ! empty( $year ) ) {
$my_year = $year;
$my_month = $wp_locale->get_month( $monthnum );
} elseif ( ! empty( $m ) ) {
$my_year = substr( $m, 0, 4 );
$my_month = $wp_locale->get_month( substr( $m, 4, 2 ) );
}
if ( empty( $my_month ) ) {
return false;
}
$result = $prefix . $my_month . $prefix . $my_year;
if ( ! $display ) {
return $result;
}
echo $result;
}
原文内容
Displays or retrieves page title for post archive based on date.
Description
Useful for when the template only needs to display the month and year, if either are available. The prefix does not automatically place a space between the prefix, so if there should be a space, the parameter value will need to have it at the end.
Parameters
$prefixstringoptional-
What to display before the title.
$displaybooloptional-
Whether to display or retrieve title.
Default:
true
Source
function single_month_title( $prefix = '', $display = true ) {
global $wp_locale;
$m = get_query_var( 'm' );
$year = get_query_var( 'year' );
$monthnum = get_query_var( 'monthnum' );
if ( ! empty( $monthnum ) && ! empty( $year ) ) {
$my_year = $year;
$my_month = $wp_locale->get_month( $monthnum );
} elseif ( ! empty( $m ) ) {
$my_year = substr( $m, 0, 4 );
$my_month = $wp_locale->get_month( substr( $m, 4, 2 ) );
}
if ( empty( $my_month ) ) {
return false;
}
$result = $prefix . $my_month . $prefix . $my_year;
if ( ! $display ) {
return $result;
}
echo $result;
}
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |
Skip to note 2 content
Codex
Month and Year on New Lines
Displays the title, placing month and year on new lines.
<p>') ?></p>Output is following 2 lines.