Description
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 = [
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => wc_get_order_types(),
'post_status' => array_keys( wc_get_is_paid_statuses() ),
];
$customer_orders = get_posts( $args );
// No Orders Found
if ( ! $customer_orders ) { return; }
// Get Unique Products Within Order History
$purch_product_ids = [];
foreach( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order->ID );
$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' );
} );
Support
Using our Google upload form:
- Describe the issue and what you’ve observed.
- Describe your expected outcome(s).
- List steps to reproduce the issue.
- Optionally attach screen-shot images or a video.
Credits
We code all of our code snippets directly. Our clients provide most of the ideas and demand for the functionality provided by our code snippets.
There are several sources one can find on Google for code that has inspired or contributed to this open-source library. Here’s some main ones:
License & Disclaimer
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.