2

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>';
    }
} 
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Giuls
  • 570
  • 11
  • 33
  • Why don't you kick the date in the item out to the screen and check if the conditional is working? Post the date. Might also want to check the date conversion is correct. – Shawn Feb 02 '19 at 21:38

1 Answers1

4

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399