Woocommerce - 检查产品创造了不到60天前

时间:2019-02-02 21:34:57

标签: php wordpress datetime woocommerce product

我想检查Woocommerce产品是否在不到60天前创建。 - 如果为真,做一些事情

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

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

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

任何帮助表示赞赏。

我的代码:

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>';
    }
} 

1 个答案:

答案 0 :(得分: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文件中。经过测试,可以正常工作。

相关问题