
本教程详细介绍了如何在 WooCommerce 中准确显示产品自发布以来经过的年、月、日时长。针对传统时间戳计算可能出现的闰年和月份天数差异导致的误差,我们采用 PHP 内置的 DateTime 和 DateInterval 对象进行精确计算。文章将提供完整的代码示例,并深入解析其工作原理,帮助您在商品详情页和商品列表页正确展示产品“年龄”。
在电子商务网站中,有时需要向用户展示产品已经发布了多长时间,例如“上架x年x月x天”。然而,传统的基于时间戳的简单数学运算(如将总秒数除以固定天数来计算年、月、日)往往会因为闰年、不同月份的天数差异而导致计算结果不准确。为了解决这一问题,php 提供了强大的 datetime 和 dateinterval 类,它们能够精确地处理日期和时间之间的复杂关系。
挑战:手动日期计算的局限性
许多开发者在计算日期差时,可能会尝试获取两个日期的 Unix 时间戳,然后计算它们的差值(秒数),再将这个秒数差值转换为年、月、日。例如:
// 错误的计算方式示例 $dateDifference = abs(strtotime($now_time) - strtotime($datetime)); $y = floor($dateDifference / (365 * 60 * 60 * 24)); // 简单地除以365天 $m = floor(($dateDifference - $y * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24)); // 简单地除以30天 // ... 这种方式无法正确处理闰年和月份天数变化
这种方法的最大问题在于,它假设一年固定为365天,一个月固定为30天。然而,实际情况是:
- 一年可能是365天或366天(闰年)。
- 一个月的天数可能是28、29、30或31天。
这些差异会导致计算结果偏离实际,尤其是在跨越多个年份或月份时,累积误差会变得明显。
解决方案:利用 PHP DateTime 和 DateInterval 对象
PHP 的 DateTime 类提供了处理日期和时间的高级功能,包括创建日期对象、格式化日期、以及最重要的——计算日期之间的差异。DateTime::diff() 方法是解决此问题的关键,它返回一个 DateInterval 对象,该对象精确地包含了两个日期之间的年、月、日、时、分、秒等所有差异信息,并且正确处理了闰年和月份天数变化。
核心代码实现
以下代码演示了如何在 WooCommerce 中集成此功能,使其在商品详情页和商品列表页显示产品的上架时长。
<?php
/**
* 获取产品上架时长的辅助函数
* 使用 DateTime 和 DateInterval 精确计算年、月、日
*
* @param WC_Product $product WooCommerce 产品对象
* @param string $format 可选,输出格式字符串,默认为 'years, months and days'
* @return string 格式化后的产品上架时长字符串
*/
function get_product_launch_duration_string( $product, $format = 'years, months and days' ) {
if ( ! $product instanceof WC_Product ) {
return '';
}
// 获取产品创建日期 (通常是发布日期)
// get_the_date() 获取当前文章/产品发布日期,格式化为 'd-m-Y'
$published_date_string = get_the_date( 'd-m-Y', $product->get_id() );
$published = new DateTime( $published_date_string );
// 获取当前日期
// current_time() 获取当前 WordPress 时间,格式化为 'd-m-Y'
$today = new DateTime( current_time( 'd-m-Y' ) );
// 计算日期间隔
$interval = $published->diff( $today );
$output = [];
// 根据需求构建输出字符串
if ( $interval->y > 0 ) {
$output[] = sprintf( _n( '%s year', '%s years', $interval->y, 'your-text-domain' ), $interval->y );
}
if ( $interval->m > 0 ) {
$output[] = sprintf( _n( '%s month', '%s months', $interval->m, 'your-text-domain' ), $interval->m );
}
if ( $interval->d > 0 ) {
$output[] = sprintf( _n( '%s day', '%s days', $interval->d, 'your-text-domain' ), $interval->d );
}
if ( empty( $output ) ) {
return __( 'Less than a day', 'your-text-domain' ); // 如果不足一天
}
// 根据格式要求组合字符串
switch ( $format ) {
case 'years, months and days':
// 示例: 1 year, 2 months and 3 days
$last_item = array_pop( $output );
if ( ! empty( $output ) ) {
return implode( ', ', $output ) . ' ' . __( 'and', 'your-text-domain' ) . ' ' . $last_item;
}
return $last_item;
case 'years, months':
// 示例: 1 year, 2 months
$output_ym = [];
if ( $interval->y > 0 ) {
$output_ym[] = sprintf( _n( '%s year', '%s years', $interval->y, 'your-text-domain' ), $interval->y );
}
if ( $interval->m > 0 ) {
$output_ym[] = sprintf( _n( '%s month', '%s months', $interval->m, 'your-text-domain' ), $interval->m );
}
return implode( ', ', $output_ym );
case 'simple':
// 示例: 1y 2m 3d
$simple_parts = [];
if ( $interval->y > 0 ) $simple_parts[] = $interval->y . 'y';
if ( $interval->m > 0 ) $simple_parts[] = $interval->m . 'm';
if ( $interval->d > 0 ) $simple_parts[] = $interval->d . 'd';
return implode( ' ', $simple_parts );
default:
// 默认输出所有有值的年、月、日
return implode( ', ', $output );
}
}
/**
* 在商品详情页显示产品上架时长
*/
add_action( 'woocommerce_single_product_summary', 'display_single_product_launch_time', 25 );
function display_single_product_launch_time() {
global $product; // 获取当前产品对象
$duration_string = get_product_launch_duration_string( $product );
if ( ! empty( $duration_string ) ) {
echo '<div class="product-launch-time">';
echo '<strong>' . __( 'Product Launch Date:', 'your-text-domain' ) . '</strong> ' . $duration_string;
echo '</div>';
}
}
/**
* 在商品循环列表页(如商店页、分类页)显示产品上架时长
*/
add_action( 'woocommerce_after_shop_loop_item', 'display_product_loop_launch_time', 20 );
function display_product_loop_launch_time() {
global $product; // 获取当前产品对象
// 可以在这里选择不同的格式,例如只显示年和月
$duration_string = get_product_launch_duration_string( $product, 'years, months' );
if ( ! empty( $duration_string ) ) {
echo '<div class="product-loop-launch-time">';
echo '<small>' . __( 'Launched:', 'your-text-domain' ) . ' ' . $duration_string . '</small>';
echo '</div>';
}
}
代码详解
-
get_product_launch_duration_string( $product, $format ) 函数:
- 这是一个辅助函数,封装了计算产品上架时长的核心逻辑。它接受一个 WC_Product 对象和可选的输出格式参数。
- $published = new DateTime( get_the_date( ‘d-m-Y’, $product->get_id() ) );:
- get_the_date( ‘d-m-Y’, $product->get_id() ) 是 WordPress 函数,用于获取指定文章(在此是产品)的发布日期。我们将其格式化为 d-m-Y(例如 01-01-2023),以便 DateTime 类能够正确解析。
- new DateTime(…) 创建了一个表示产品发布日期的 DateTime 对象。
- $today = new DateTime( current_time( ‘d-m-Y’ ) );:
- current_time( ‘d-m-Y’ ) 是 WordPress 函数,用于获取当前站点时间(已考虑时区设置),同样格式化为 d-m-Y。
- new DateTime(…) 创建了一个表示当前日期的 DateTime 对象。
- $interval = $published->diff( $today );:
- 这是核心步骤。diff() 方法计算 $published 和 $today 两个 DateTime 对象之间的差异,并返回一个 DateInterval 对象。这个对象会自动处理闰年和月份天数不一致的问题。
- $interval->y, $interval->m, $interval->d:
- DateInterval 对象有多个属性,其中 y 代表年,m 代表月,d 代表日。它们直接提供了精确的差值。
- 国际化 (_n, __):
- _n() 用于处理单复数形式的字符串,例如“1 year”与“2 years”。
- __(‘string’, ‘your-text-domain’) 用于标记字符串以便翻译。请将 your-text-domain 替换为您主题或插件的实际文本域。
- 输出格式化:函数内部根据 $format 参数,提供了几种常见的输出格式,例如 1 year, 2 months and 3 days 或 1y 2m 3d,您可以根据需求进行扩展。
-
display_single_product_launch_time() 函数:
- 通过 add_action( ‘woocommerce_single_product_summary’, ‘…’, 25 ); 钩子,将此函数挂载到 WooCommerce 单个产品页面的摘要部分。优先级 25 决定了它在其他元素中的显示顺序。
- global $product; 用于获取当前正在查看的产品对象。
- 调用 get_product_launch_duration_string() 获取格式化后的时长字符串并输出。
-
display_product_loop_launch_time() 函数:
- 通过 add_action( ‘woocommerce_after_shop_loop_item’, ‘…’, 20 ); 钩子,将此函数挂载到 WooCommerce 产品循环列表(如商店页、分类页)的每个产品下方。优先级 20 决定了其显示位置。
- 同样使用 global $product; 获取产品对象。
- 在此示例中,我们特意为循环列表页选择了 years, months 的格式,以保持简洁。您可以根据页面布局和需求进行调整。
注意事项与最佳实践
-
文本域 (Text Domain):
- 在 __ 和 _n 函数中,务必将 your-text-domain 替换为您主题或插件实际使用的文本域。这对于网站的国际化(多语言支持)至关重要。
-
输出格式定制:
- get_product_launch_duration_string 函数提供了基础的输出格式,您可以根据自己的设计需求,修改或添加更多的格式选项,例如只显示年,或者只显示月(如果不足一年)。
-
钩子位置与优先级:
- woocommerce_single_product_summary 和 woocommerce_after_shop_loop_item 是常用的 WooCommerce 动作钩子,用于在特定位置插入内容。您可以查阅 WooCommerce 官方文档,了解更多可用的钩子,并根据需要调整优先级(数字越大,执行越晚)。
-
性能考量:
- DateTime 类的操作通常是高效的。在产品循环中,每次迭代都会执行一次日期计算,对于大多数网站而言,这不会造成明显的性能问题。
-
日期来源:
- 本教程使用了 get_the_date() 来获取产品发布日期。如果您的产品创建日期存储在其他地方(例如自定义字段),您需要相应地调整日期获取逻辑。
- WC_Product 对象本身也包含 get_date_created() 方法,它返回一个 WC_DateTime 对象(DateTime 的子类),可以直接用于 diff() 方法,例如:
$published = $product->get_date_created(); // 返回 WC_DateTime 对象 $today = new WC_DateTime(); // 获取当前 WC_DateTime 对象 $interval = $published->diff($today);
登录后复制这种方式在处理 WooCommerce 内部日期和时区时可能更具一致性。本教程的 get_the_date() 方案同样有效且简洁。
总结
通过利用 PHP 的 DateTime 和 DateInterval 类,我们可以轻松且精确地计算出 WooCommerce 产品的上架时长。这种方法避免了手动日期计算中常见的闰年和月份天数差异问题,确保了显示结果的准确性。将这些功能集成到 WooCommerce 的适当钩子中,可以无缝地在您的产品页面和列表页展示这些有价值的信息,提升用户体验。
以上就是精确计算 WooCommerce 产品上架时长:年、月、日显示教程的详细内容,更多请关注php中文网其它相关文章!