mirror of
https://gh.wpcy.net/https://github.com/mainwp/Code-Snippets-Functions.git
synced 2026-05-02 12:02:25 +08:00
https://stackoverflow.com/questions/68005939/how-to-avoid-buying-the-same-product-again-in-woocommerce-by-adding-products-to/68007576
35 lines
1.2 KiB
Text
35 lines
1.2 KiB
Text
function action_woocommerce_check_cart_items() {
|
|
// Retrieve the current user object
|
|
$current_user = wp_get_current_user();
|
|
|
|
// Initialize
|
|
$flag = false;
|
|
|
|
// Loop through cart items
|
|
foreach( WC()->cart->get_cart() as $cart_item ) {
|
|
// Check for variantions
|
|
$product_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
|
|
|
|
// Checks if a user (by email or ID or both) has bought an item
|
|
if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) {
|
|
// Flag becomes true
|
|
$flag = true;
|
|
|
|
// Break loop
|
|
break;
|
|
}
|
|
}
|
|
|
|
// True
|
|
if ( $flag ) {
|
|
// Clear all other notices
|
|
wc_clear_notices();
|
|
|
|
// Avoid checkout display an error notice
|
|
wc_add_notice( __( 'My custom error message', 'woocommerce' ), 'error' );
|
|
|
|
// Optional: remove proceed to checkout button
|
|
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
|
|
}
|
|
}
|
|
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );
|