Woohoo, I actually got it working. Had to use new DateTime()
with the variables and $diff->days
to display the days. Now just to prevent the function from duplicating the meta information in the rare cases where some store manager changes the status by accident back and forth between completed and some other status. Ideas?
function mysite_woocommerce_order_completed( $order_id ) {
$order = NULL;
$order_created_date = NULL;
$order = wc_get_order($order_id);
$order_created_date = $order->order_date;
$order_created_date = new DateTime($order_created_date);
$order_items = $order->get_items();
foreach ($order_items as $item_id => $order_item) {
$product_id = $order_item['product_id'];
$product_date = get_the_time( 'Y-m-d H:i:s', $product_id );
$product_date = new DateTime($product_date);
$diff = date_diff( $product_date, $order_created_date );
// +1 to days to start counting same day sales from 1 day
wc_add_order_item_meta( $item_id, '_days_to_purchase', 1 + $diff->days );
}
}
add_action( 'woocommerce_order_status_completed', 'mysite_woocommerce_order_completed', 10, 1 )