export_date_options()
云策文档标注
概述
export_date_options() 函数用于为指定文章类型生成导出时的日期选项字段。它从数据库中查询文章日期,并输出格式化的月份和年份选项。
关键要点
- 函数接受一个参数 $post_type,默认为 'post',用于指定要导出日期选项的文章类型。
- 通过 wpdb::get_results() 和 wpdb::prepare() 安全查询数据库,获取指定文章类型的非草稿文章的年份和月份。
- 使用 WP_Locale::get_month() 获取本地化的月份名称,结合 zeroise() 和 esc_attr() 格式化输出选项。
- 如果查询结果为空或仅包含无效数据(如年份为0),函数会提前返回,不输出任何内容。
代码示例
function export_date_options( $post_type = 'post' ) {
global $wpdb, $wp_locale;
$months = $wpdb->get_results(
$wpdb->prepare(
"SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
FROM $wpdb->posts
WHERE post_type = %s AND post_status != 'auto-draft'
ORDER BY post_date DESC",
$post_type
)
);
$month_count = count( $months );
if ( ! $month_count || ( 1 === $month_count && 0 === (int) $months[0]->month ) ) {
return;
}
foreach ( $months as $date ) {
if ( 0 === (int) $date->year ) {
continue;
}
$month = zeroise( $date->month, 2 );
printf(
'<option value="%1$s">%2$s</option>',
esc_attr( $date->year . '-' . $month ),
$wp_locale->get_month( $month ) . ' ' . $date->year
);
}
}
原文内容
Creates the date options fields for exporting a given post type.
Parameters
$post_typestringrequired-
The post type. Default
'post'.
Source
function export_date_options( $post_type = 'post' ) {
global $wpdb, $wp_locale;
$months = $wpdb->get_results(
$wpdb->prepare(
"SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
FROM $wpdb->posts
WHERE post_type = %s AND post_status != 'auto-draft'
ORDER BY post_date DESC",
$post_type
)
);
$month_count = count( $months );
if ( ! $month_count || ( 1 === $month_count && 0 === (int) $months[0]->month ) ) {
return;
}
foreach ( $months as $date ) {
if ( 0 === (int) $date->year ) {
continue;
}
$month = zeroise( $date->month, 2 );
printf(
'<option value="%1$s">%2$s</option>',
esc_attr( $date->year . '-' . $month ),
$wp_locale->get_month( $month ) . ' ' . $date->year
);
}
}
Changelog
| Version | Description |
|---|---|
| 3.1.0 | Introduced. |