Previously purchased item cart and checkout warning

Notifies the customer whenever they are about to check out an item they’ve already purchased.

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

} );

Instructions for Previously purchased item cart and checkout warning

  1. Log into a staging or locally hosted clone of your site.
  2. Install and activate Code Snippets plugin.
  3. WP Admin > Snippets > Add New
  4. Copy and paste the code from the section above.
  5. Check to ensure formatting came over properly.
  6. Customize the code as desired.
  7. Add a meaningful title.
  8. Select whether to run on front-end or back-end (or both).
  9. Click “Save and Activate”.
  10. Test your site to ensure it works.
  11. Disable if any problems, or recover.
  12. Repeat for live environment.

Need help modifying Previously purchased item cart and checkout warning?

Contact me. I can help with fitting projects or refer to my partner.

License

All code snippets are licensed GPLv2 (or later) matching WordPress licensing.

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.

Disclaimer of warranty