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