Have you ever noticed how Amazon displays a notice indicating the last item you purchased when you revisit a product page? This subtle yet effective feature provides a personalized touch and enhances the shopping experience for users. Now, you can implement a similar functionality in your WooCommerce store to delight your customers and encourage repeat purchases.

Implementing the Last Purchased Item Notice

To achieve this, we’ll utilize a custom code snippet that displays a notice indicating the last time the customer purchased the viewed product. Let’s dive into the details.

add_action( 'woocommerce_before_single_product', 'wc_last_purchased_notice', 9 );

function wc_last_purchased_notice() {
    if ( ! is_user_logged_in() ) {
        return;
    }

    if ( ! is_product() ) {
        return;
    }

    global $product;
    if ( ! is_a( $product, '\WC_Product' ) ) {
        return;
    }

    $customer_orders   = wc_get_orders(
        array(
            'customer' => get_current_user_id(),
            'status'   => array( 'processing', 'completed' ),
        )
    );
    $target_product_id = $product->get_id();

    foreach ( $customer_orders as $order ) {
        $order_items = $order->get_items();
        foreach ( $order_items as $item ) {
            if ( $item->get_product_id() === $target_product_id ) {
                $order_date = gmdate('M d, Y', $order->get_date_created()->getOffsetTimestamp() );
                wc_add_notice( wp_kses_post( sprintf( esc_html__( 'You last purchased this item on %s', 'woocommerce' ), $order_date ) . '<br/><a style="text-decoration:underline;" href="' . esc_url( $order->get_view_order_url() ) . '">' . esc_html__( 'View order details', 'woocommerce' ) . '</a>' ), 'notice' );
                return;
            }
        }
    }
}

How to Use the Code snippet

You can implement this snippet by following on of these steps:

  1. Child Theme: If you’re using a custom child theme, you can add the snippet to the functions.php file of your child theme. This ensures that the functionality remains intact even when you update your theme.
  2. Custom Plugin: A better way, you can create a custom plugin to add the snippet. Creating a custom plugin allows you to keep your code separate from the theme files, making it easier to manage and maintain. You can use our online tool WP Plugin Creator to generate a custom plugin with the snippet included. Simply paste the snippet into the plugin code editor, specify the plugin name, and download the generated plugin zip file.

By following these steps, you can seamlessly integrate the last purchased item notice feature into your WooCommerce store, providing users with a personalized shopping experience reminiscent of major e-commerce platforms like Amazon. Enhance customer engagement and encourage repeat purchases with this simple yet effective addition to your online store.