Woocommerce - Check if product was created less than 60 days ago

守給你的承諾、 提交于 2021-02-20 04:08:10

问题


I want to check if a Woocommerce product was created less than 60 days ago. - If true, do something.

I am obtaining the date the product was created in backend/admin using the official Woocmmerce function $product->get_date_created.

My code partially works, but it seems to be checking if $product->get_date_created literally contains the value 60 instead of perfoming the calculation and minusing 60 days from the current DateTime.

I have come to this conclusion because my IF statement runs true and is applied to all products with "60" in the actual DateTime string. (e.g. 12/31/2060)...this is not what I want.

Any help appreciated.

My code:

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:


I have revisited a bit your code using the WC_DateTime methods instead, which will keep the time zone settings from the shop:

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

Code goes in function.php file of your active child theme (or active theme). Tested and works.



来源:https://stackoverflow.com/questions/54497749/woocommerce-check-if-product-was-created-less-than-60-days-ago

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!