Last active
September 20, 2023 08:18
-
-
Save obiPlabon/76bb161ec3c0f4e8eeb3d70c03545961 to your computer and use it in GitHub Desktop.
Prevent WooCommerce to add more than 1 item in cart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Simple & concise Solution | |
*/ | |
function op_block_add_to_cart() { | |
wc_add_notice( sprintf( | |
/** translators: %1$s is cart url, %2$s is checkout url */ | |
esc_html__( 'You cannot purchase more than 1 item at a time. %1$s or %2$s', 'op' ), | |
'<a href="' . esc_url( wc_get_cart_url() ) . '">' . esc_html__( 'View cart', 'op' ) . '</a>', | |
'<a href="' . esc_url( wc_get_checkout_url() ) . '">' . esc_html__( 'checkout', 'op' ) . '</a>' | |
), 'error' ); | |
return WC()->cart->is_empty(); | |
} | |
add_filter( 'woocommerce_add_to_cart_validation', 'op_block_add_to_cart' ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Forget about 'woocommerce_add_to_cart_validation' filter hook | |
* that's why created this solution :P | |
*/ | |
function op_block_add_to_cart( $cart_item_key ) { | |
if ( count( WC()->cart->get_cart() ) > 1 ) { | |
// Remove latest item from cart to prevent side effect | |
WC()->cart->remove_cart_item( $cart_item_key ); | |
// Show notification to user | |
throw new Exception( sprintf( | |
/** translators: %1$s is cart url, %2$s is checkout url */ | |
esc_html__( 'You cannot purchase more than 1 item at a time. %1$s or %2$s', 'op' ), | |
'<a href="' . esc_url( wc_get_cart_url() ) . '">' . esc_html__( 'View cart', 'op' ) . '</a>', | |
'<a href="' . esc_url( wc_get_checkout_url() ) . '">' . esc_html__( 'checkout', 'op' ) . '</a>' | |
) ); | |
} | |
} | |
add_action( 'woocommerce_add_to_cart', 'op_block_add_to_cart' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment