Remove Product From Cart Programmatically WooCommerce

To remove a product from the cart programmatically in WooCommerce, you can use the woocommerce_cart_item_removed and woocommerce_before_calculate_totals hooks. Here’s how you can do it:

Step 1: Hook into woocommerce_cart_item_removed Add the following code to your theme’s functions.php file or a custom plugin:

function custom_remove_product_from_cart($cart_item_key, $cart)
{
    // Get the product ID to be removed from the cart
    $product_id = $cart->cart_contents[$cart_item_key]['product_id'];

    // Check if you want to remove a specific product based on its ID
    if ($product_id === YOUR_PRODUCT_ID_TO_REMOVE) {
        unset($cart->cart_contents[$cart_item_key]);
    }
}
add_action('woocommerce_cart_item_removed', 'custom_remove_product_from_cart', 10, 2);

Replace YOUR_PRODUCT_ID_TO_REMOVE with the actual product ID you want to remove from the cart.

Step 2: Hook into woocommerce_before_calculate_totals Add the following code to your theme’s functions.php file or a custom plugin:

function custom_remove_product_from_cart_on_calculate_totals($cart)
{
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }

    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        // Get the product ID to be removed from the cart
        $product_id = $cart_item['product_id'];

        // Check if you want to remove a specific product based on its ID
        if ($product_id === YOUR_PRODUCT_ID_TO_REMOVE) {
            $cart->remove_cart_item($cart_item_key);
        }
    }
}
add_action('woocommerce_before_calculate_totals', 'custom_remove_product_from_cart_on_calculate_totals', 10, 1);

Again, replace YOUR_PRODUCT_ID_TO_REMOVE with the actual product ID you want to remove from the cart.

Step 3: Save Changes and Test Save the changes to your functions.php file or custom plugin. Now, when you add the specific product with the provided product ID to the cart, it will be removed automatically.

Remember to test the functionality thoroughly to ensure it’s working as expected. Always make sure you have a backup of your site before making any significant changes to the code.

Categories

Related Blogs

Add Admin User in WordPress By FTP

Creating an admin user in WordPress through an FTP client is not a direct method since user accounts are managed through the WordPress database and not through files on the server. To add an admin user, you’ll need to use a different approach. Here’s how you can do it:

Disable plugin update in WordPress

While it’s generally not recommended to disable plugin updates in WordPress due to security and functionality improvements, there might be specific cases where you need to prevent certain plugins from updating. Keep in mind that doing so may leave your site vulnerable to security issues and may cause compatibility problems with future WordPress versions.