add_action( 'template_redirect', function() {
// Authenticated Users Only
if( ! get_current_user_id() ) {
return;
}
// WooCommerce Cart And Checkout Only
if( ! function_exists( 'is_cart' ) || ! function_exists( 'is_checkout' ) ) {
return;
}
if( ! is_cart() && ! is_checkout() ) {
return;
}
// Get User's Previous Purchases
$args = [
'limit' => -1,
'customer_id' => get_current_user_id(),
'status' => array_keys( wc_get_is_paid_statuses() ),
'type' => 'shop_order',
];
$orders = wc_get_orders( $args );
// No Orders Found
if ( ! $orders ) {
return;
}
// Get Unique Products Within Order History
$purch_product_ids = [];
foreach( $orders as $order ) {
$items = $order->get_items();
foreach( $items as $item ) {
$purch_product_ids[] = $item->get_product_id();
}
}
$purch_product_ids = array_unique( $purch_product_ids );
// Find Conflicts With Cart Items
$errors = [];
foreach( WC()->cart->get_cart() as $cart_item ) {
$cart_product_id = $cart_item['product_id'];
if( in_array( $cart_product_id, $purch_product_ids ) ) {
$_product = wc_get_product( $cart_item['data']->get_id() );
$errors[] = sprintf(
'<a href="%s">%s</a>',
get_permalink( $cart_product_id ),
$_product->get_title()
);
}
}
// No Conflicts
if( ! $errors ) {
return;
}
// Handle Conflicts
$message = sprintf(
'
<strong>Warning:</strong>
We found item(s) in your <a href="%s">cart</a>
that you have already purchased:<br />
%s<br />
<a class="button" href="%s">%s</a>
',
wc_get_cart_url(),
implode( ' & ', $errors ),
wc_get_account_endpoint_url( 'orders' ),
'Visit My Orders'
);
wc_add_notice( $message, 'error' );
} );
Previously purchased item cart and checkout warning
Notifies the customer whenever they are about to check out an item they’ve already purchased.
How to use
- Log into a staging, development, or locally hosted clone of your site
- Install and activate Code Snippets
- WP Admin > Snippets > Add New
- Copy and paste the code from the Description tab above
- Check to ensure formatting came over properly and no syntax errors show up in the editor
- Customize the code as desired
- Add a meaningful title
- Select whether to run on front-end or back-end (or both)
- Click “Save and Activate”
- Test your site to ensure it works
- Disable if any problems, or recover
- Repeat for live environment
License
All code snippets are licensed GPLv2 (or later) matching WordPress licensing.
Disclaimer of warranty:
Except when otherwise stated in writing the copyright holders and/or other parties provide the program as-is without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose.
Support
- Describe the issue and what you’ve observed.
- Describe your expected outcome(s).
- List steps to reproduce the issue.
- Optionally provide screen-shot or video URLs.
- Email to [email protected]
