【问题标题】:Woocommerce - Check if product was created less than 60 days agoWoocommerce - 检查产品是否在 60 天内创建
【发布时间】:2019-02-02 21:34:57
【问题描述】:

我想检查 Woocommerce 产品是否是在 60 天前创建的。 - 如果是真的,做点什么。

我正在使用官方 Woocmmerce 函数$product->get_date_created 在后端/管理中获取产品的创建日期。

我的代码部分有效,但它似乎在检查 $product->get_date_created 字面上是否包含值 60,而不是执行计算并从 当前 DateTime 减去 60 天.

我得出这个结论是因为我的 IF 语句运行正确,并且适​​用于实际 DateTime 字符串中带有“60”的所有产品。 (例如 12/31/2060)...这不是我想要的。

任何帮助表示赞赏。

我的代码:

add_action( 'woocommerce_before_shop_loop_item_title', 'display_new_loop_woocommerce' );

function display_new_loop_woocommerce() {
    global $product;

  // Get the date for the product published and current date
  $start = date( 'n/j/Y', strtotime( $product->get_date_created() ));
  $today = date( 'n/j/Y' );

  // Get the date for the start of the event and today's date.
  $start      = new \DateTime( $start );
  $end        = new \DateTime( $today );

    // Now find the difference in days.
  $difference = $start->diff( $end );
  $days      = $difference->d;

    // If the difference is less than 60, apply "NEW" label to product archive.             
    if ( $days = (60 < $days) ) {
        echo '<span class="limited">' . __( 'NEW', 'woocommerce' ) . '</span>';
    }
} 

【问题讨论】:

  • 为什么不将项目中的日期踢到屏幕上并检查条件是否有效?发布日期。可能还想检查日期转换是否正确。

标签: php wordpress datetime woocommerce product


【解决方案1】:

我已经改用WC_DateTime 方法重新访问了您的代码,这将保留商店的时区设置:

add_action( 'woocommerce_before_shop_loop_item_title', 'display_new_loop_woocommerce' );
function display_new_loop_woocommerce() {
    global $product;

    // Get the date for the product published and current date
    $datetime_created  = $product->get_date_created(); // Get product created datetime
    $timestamp_created = $datetime_created->getTimestamp(); // product created timestamp

    $datetime_now      = new WC_DateTime(); // Get now datetime (from Woocommerce datetime object)
    $timestamp_now     = $datetime_now->getTimestamp(); // Get now timestamp

    $time_delta        = $timestamp_now - $timestamp_created; // Difference in seconds
    $sixty_days        = 60 * 24 * 60 * 60; // 60 days in seconds

    // If the difference is less than 60, apply "NEW" label to product archive.
    if ( $time_delta < $sixty_days ) {
        echo '<span class="limited">' . __( 'NEW', 'woocommerce' ) . '</span>';
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 2021-12-04
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多