WordPress 获取时间的方法代码
在 WordPress 中,你可以使用多种方法来获取当前时间或日期。
以下是几种常用的WordPress 获取时间的方法代码:
1. 使用 WordPress 核心函数
// 获取当前时间(基于 WordPress 时区设置)
$current_time = current_time('timestamp'); // 返回 Unix 时间戳
$current_time_mysql = current_time('mysql'); // 返回 MySQL 格式的时间 'Y-m-d H:i:s'
// 带格式的输出
$formatted_time = current_time('Y-m-d H:i:s'); // 返回指定格式的时间字符串
2. 使用 PHP 原生函数
// 获取服务器时间
$server_time = time(); // Unix 时间戳
$server_date = date('Y-m-d H:i:s'); // 格式化日期时间
// 获取 GMT/UTC 时间
$gmt_time = gmdate('Y-m-d H:i:s');
3. 获取特定格式的时间
// 使用 date_i18n() 函数(本地化时间)
$localized_time = date_i18n('Y-m-d H:i:s');
// 常用格式
$year = date_i18n('Y'); // 年
$month = date_i18n('m'); // 月
$day = date_i18n('d'); // 日
$hour = date_i18n('H'); // 时
$minute = date_i18n('i'); // 分
$second = date_i18n('s'); // 秒
4. 获取文章发布时间
// 在循环中获取文章发布时间
if (have_posts()) {
while (have_posts()) {
the_post();
$post_time = get_the_time('Y-m-d H:i:s'); // 获取文章发布时间
$modified_time = get_the_modified_time('Y-m-d H:i:s'); // 获取文章最后修改时间
}
}
5. 时间差计算
// 计算时间差(如"发表于3天前")
function time_ago($time) {
return human_time_diff($time, current_time('timestamp')) . ' ago';
}
// 使用示例
$post_date = get_the_time('U'); // 获取文章发布时间戳
echo '发表于 ' . time_ago($post_date);
6. 设置和获取时区
// 获取 WordPress 时区设置
$timezone_string = get_option('timezone_string');
$gmt_offset = get_option('gmt_offset');
// 设置时区(在插件或主题中使用)
date_default_timezone_set($timezone_string);
注意事项
- WordPress 推荐使用
current_time()而不是 PHP 原生的time()或date(),因为前者会考虑 WordPress 的时区设置 - 如果要显示给用户看的时间,建议使用
date_i18n()以支持多语言 - 在主题或插件开发中,考虑使用 WordPress 的时间函数以确保一致性
以上方法可以根据具体需求选择使用,大多数情况下 current_time()和 date_i18n()是最常用的函数。