0

I am trying to implement a function to be able to update a cart item with custom attributes (displayed in input fields in the product view).

My strategy is to remove the existing item by adding a link in the cart page like this:

/product/my-product/?edit_item=7326b7ed789bc9ae1ddfe97fd0abcf72 (the key)

Then I'd like to remove this product once the user clicks on "add to cart".

I have tried this solution here (first answer):

Remove a specific cart item when adding to cart a specific product in Woocommerce

and this one (also first answer):

Wordpress. Woocommerce. Action hook BEFORE adding to cart

and I have this code now:

function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {
GLOBAL $woocommerce;
$keytoremove=$_GET['edit_item'];

    // do your validation, if not met switch $passed to false
    if ( 1 != 2 ){
        $passed = true;
        // $woocommerce->cart->remove_cart_item($keytoremove);      
        wc_add_notice( __( $keytoremove. ' was removed', 'textdomain' ), 'notice' );
    }
    return $passed;

}
add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );

The Problem is that I cannot access the Variable ... $_GET['edit_item'] is empty. So I get the notice " was removed". Adding a hidden form field did not help either.

How can I access this variable? Thanks!

Mister Woyng
  • 391
  • 2
  • 16

1 Answers1

0

I have now stored the key of the product-to-be-removed in the session und delete it after removal. Looks like this:

I vave defined the Session Variable:

$_SESSION['keytoremove'] = $_GET['edit_item'];

and later my function does the following:

function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {

GLOBAL $woocommerce;

if ( isset ($_SESSION['keytoremove']) ) {
    $keytoremove=$_SESSION['keytoremove'];
    $passed = true;
    $woocommerce->cart->remove_cart_item($keytoremove);
    wc_add_notice( __( $keytoremove. ' was removed from the cart', 'textdomain' ), 'notice' );
    unset ($_SESSION["keytoremove"]);
    }
return $passed;
}

add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );

Tested and works. Maybe there is a better solution avoiding the use of $_SESSION-Vars?

Mister Woyng
  • 391
  • 2
  • 16