skip to Main Content

Ive got a page where the user fills out a form and it creates a custom woocommerce product

The user can only have this one type of product so I have made it so the product is put into the category “quotes”

However to ensure they have not already got it in the cart I have a script that empties the cart before adding the product

//check if product already in cart

WC()->cart->empty_cart(true);
WC()->session->set('cart', array());
if ( WC()->cart->get_cart_contents_count() == 0 ) {

// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );

}
    wp_redirect( home_url('/checkout/') ); exit;  

But as there is an “addon” category too, I dont want any of those products being removed from the cart, only the products assigned to “quote” category

I have seen lots of ways to remove specific product from the cart, but I not anything where you can remove products belonging to a category.

I came up with the below using Exclude certain categories when automatically adding products to the cart WooCommerce

foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Get product id
        $prod_id = $cart_item['data']->get_id();

$category = quotes;

if( has_term( $category, 'product_cat', $prod_id ) ) {

 WC()->cart->remove_cart_item($prod_id);

}
}

    wp_redirect( home_url('/checkout/') ); exit;

and

    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $prod_id =  wc_get_product( $values['data']->get_id()); 
$category = quotes;

if( has_term( $category, 'product_cat', $prod_id ) ) {

 WC()->cart->remove_cart_item($prod_id);

}
}

But this does not work either.

Can anyone assist please

EDIT:

The product is created via a HTML/JQUERY form

Here is the PHP at the bottom of the form

// Add the shortcode to WordPress. 
add_shortcode('vehicle-quote', 'vehicle_quote');

function vehicle_quote_add_post(){
    if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'post' ){
        if ( !is_user_logged_in() )
            return;
        global $current_user;

        $user_id        = $current_user->ID;
        $post_title     = $_POST['post-title'];
        $post_content   = $_POST['posttext'];
        $tags           = $_POST['tags'];

        $length = filter_var($_POST['outlengthquestion'], FILTER_SANITIZE_STRING);
        $timefor = filter_var($_POST['outtimefor'], FILTER_SANITIZE_STRING);
        $essential = filter_var($_POST['outessential'], FILTER_SANITIZE_STRING);
        $contents = filter_var($_POST['outcontents'], FILTER_SANITIZE_STRING);
        $sterio = filter_var($_POST['outsterio'], FILTER_SANITIZE_STRING);


    global $error_array;
        $error_array = array();

        if (empty($post_title)) $error_array[]='Please add a title.';


        if (count($error_array) == 0){

            $post_id = wp_insert_post( array(
                'post_author'   => $user_id,
                'post_title'    => $post_title,
                'post_type'     => 'product',
                'meta_input' => array(
                'timefor_period' => $timefor,
                'length_level' => $length,          
                'essential' => $essential,
                'contents' => $contents,
                'sterioprotect' => $sterio,

            ),
        'post_status'   => 'publish'
        ) 
        );          



// select ID
$numberAsString = number_format($price, 2);
$product_id = $post_id;
      wp_set_object_terms( $post_id, 'Quotes', 'product_cat' );
      update_post_meta($post_id, '_regular_price', $numberAsString );
      add_post_meta($post_id, '_price', $numberAsString );
      add_post_meta($post_id, '_stock_status', 'instock' );
      add_post_meta($post_id, '_manage_stock', 'yes');
      add_post_meta ($post_id, '_stock', 1);





add_action( 'woocommerce_before_calculate_totals', 'remove_from_cart', 10, 1 );
//check if product already in cart


WC()->cart->add_to_cart( $product_id );

/*}  */
    wp_redirect( home_url('/checkout/') ); exit;  


        } else {

        }
    }
}

add_action('init','vehicle_quote_add_post');

2

Answers


  1. To remove cart item you should use $cart_item_key instead of $prod_id

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    
         WC()->cart->remove_cart_item( $cart_item_key );
    
    }
    
    Login or Signup to reply.
  2. function remove_from_cart( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        /********** SETTINGS **********/
        $remove_categories = array( 'quotes' ); // Remove these categories
    
        /********** LOOP THROUGH CART ITEMS **********/
    
        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
            // Get product id
            $product_id = $cart_item['product_id'];
    
            // Check if product belongs to a certain category
            if( has_term( $remove_categories, 'product_cat', $product_id ) ) {
                $cart->remove_cart_item( $cart_item_key );
            }
        }
    }
    add_action( 'woocommerce_before_calculate_totals', 'remove_from_cart', 10, 1 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search