This snippet allows logged in users to see a history of previous purchases of the currently viewed product under the add to cart button. This snippet is particularly useful to remind customers of when they have previously purchased this product. The date of the purchase is hyperlinked to the order view page. You’ll also notice the quantity of the products ordered is appended as a suffix to the link. Keep in mind, this will only the order history if the status of the order is set to complete. If you are finding previous product orders are not showing, it may be the order status you need to look at.
/**
* Snippet Name: WooCommerce Show Previous Orders Of Product On Single Product Template
* Snippet Author: ecommercehints.com
*/
add_action( 'woocommerce_after_add_to_cart_form', 'ecommercehints_show_product_order_history', 10 );
function ecommercehints_show_product_order_history() {
global $product, $post;
echo 'Previous Purchases
';
$orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order',
'post_status' => 'wc-completed'
) );
foreach ($orders as $order) {
$order = new WC_Order( $order->ID );
$order_data = $order->get_data();
$order->get_date_completed();
$public_view_order_url = esc_url( $order->get_view_order_url() );
$items = $order->get_items();
foreach( $items as $item ) {
$product_id = $item['product_id'];
$quantity = $item->get_quantity();
if ( $post->ID == $product_id ) {
echo '- ' . $order_date . ' ×' . $quantity . '
';
}
}
}
echo '