Skip to content

Instantly share code, notes, and snippets.

@yanknudtskov
Created May 5, 2020 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanknudtskov/1ac6fcfc209cd8e0ca52bdb2490d0d25 to your computer and use it in GitHub Desktop.
Save yanknudtskov/1ac6fcfc209cd8e0ca52bdb2490d0d25 to your computer and use it in GitHub Desktop.
WooCommerce Cart Validation. How to validate products being added to cart, before they are added.
<?php
add_filter( 'woocommerce_add_to_cart_validation', 'yanco_validate_add_cart_item', 10, 5 );
function yanco_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations = '' ) {
$post_title = get_the_title( $product_id );
// Items in cart, test if the product has already been added to the cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
// Test if it's a non-virtual product
if( $_product->is_virtual() === false ) {
if ( $_product->get_id() == $product_id ) {
$passed = false; // We found the item in the cart already
}
}
}
} else {
// if no products in cart, passed = true
$passed = true;
}
// do your validation, if not met switch $passed to false
if ( $passed === false ) {
wc_add_notice( __( '<strong>Du kan ikke tilføje ' . $post_title . ' til kurven da det allerede er lagt i kurven.</strong><br>Hvis du ønsker at tilføje tilvalg skal du fjerne ' . $post_title . ' fra kurven og tilføje det med tilvalg.<br>Hvis du ønsker at ændre antallet af kuverter skal du blot ændre antallet i kurven.', 'woocommerce' ), 'error' );
}
return $passed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment