WooCommerce Actions and Filters to Manipulate the Cart
Welcome to the second article in the series on Mastering WooCommerce Actions and Filters. In the previous article, even though it was very basic, we covered handling a customer’s billing and shipping address as well as what happens when a customer registers through WooCommerce and it sends them to a third party website, like Salesforce.
In this second article, we will manipulate the cart in some clever ways with real world scenarios you may encounter while creating your eCommerce website using WooCommerce.
Key Takeaways
- The article provides detailed instructions on how to manipulate the WooCommerce cart using actions and filters, including adding and removing products programmatically, emptying the cart, and setting up an incentive product system.
- Adding a product to the cart programmatically only requires one line of code, but it’s crucial not to run this on an action that executes on every page, like the template_redirect action.
- Removing a product from the cart programmatically is more complex than adding one. The code provided cycles through each product in the cart and removes the specified product.
- The article demonstrates how to create a button that empties the cart programmatically, using the woocommerce_proceed_to_checkout action.
- The article provides a real-world scenario of building an incentive product system, where a product is given away to customers who meet specific requirements, such as having a minimum total amount for an order or a product from a specific category.
Adding a Product to the Cart Programatically
Adding a product to the cart programatically only takes one line of code. The only brainstorming you’ll be doing is deciding when or why you’ll want to do it. We’ll talk more about this later in the third part of this article, when we work on our real world scenario.
All it takes to add a product to the cart is the following:
<span><span><?php </span></span><span><span>// Takes the Product ID and the Quantity </span></span><span><span>WC()->cart->add_to_cart( 73, 1 );</span></span>
As a note of caution, make sure you don’t run this on an action that runs on every page, like the template_redirect action or you’ll be adding one of these products to the cart every page load or you reloads. Avoid doing this whenever possible:
<span><span><?php </span></span><span><span>// Takes the Product ID and the Quantity </span></span><span><span>WC()->cart->add_to_cart( 73, 1 );</span></span>
Removing a Product from the Cart Programatically
I’ve seen this question being asked an infinite number of times in various forums and websites with very little answers. Hopefully this will help you the next time you want to remove a product from the cart and again, the only brainstorming you’ll be doing is when or why you would want to remove a product from the cart. The following code will prevent anyone from checking out with a product from your store. I don’t know why you would want to do something like that but it will demonstrate the steps for removing the product from the cart which is not as simple as the previous example when we added the product to the cart.
<span><span><?php </span></span><span><span>// template_redirect runs once for every page so you'll be </span></span><span><span>// increasing the quantity by one on every page load </span></span><span><span>add_action( 'template_redirect', 'add_random_product' ); </span></span><span><span>function add_random_product() { </span></span><span> <span>WC()->cart->add_to_cart( 73, 1 ); </span></span><span><span>}</span></span>
Emptying the Cart Programatically
To better illustrate how to empty the cart programatically, let’s add a button to the cart which would allow customers to click on it and clear their cart.

Let’s use the woocommerce_proceed_to_checkout action an echo our very own ‘Submit’ button which will clear the cart for the current customer.
<span><span><?php </span></span><span><span>add_action( 'template_redirect', 'remove_product_from_cart' ); </span></span><span><span>function remove_product_from_cart() { </span></span><span> <span>// Run only in the Cart or Checkout Page </span></span><span> <span>if( is_cart() || is_checkout() ) { </span></span><span> <span>// Set the product ID to remove </span></span><span> <span>$prod_to_remove = 56; </span></span><span> </span><span> <span>// Cycle through each product in the cart </span></span><span> <span>foreach( WC()->cart->cart_contents as $prod_in_cart ) { </span></span><span> <span>// Get the Variation or Product ID </span></span><span> <span>$prod_id = ( isset( $prod_in_cart['variation_id'] ) && $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id']; </span></span><span> </span><span> <span>// Check to see if IDs match </span></span><span> <span>if( $prod_to_remove == $prod_id ) { </span></span><span> <span>// Get it's unique ID within the Cart </span></span><span> <span>$prod_unique_id = WC()->cart->generate_cart_id( $prod_id ); </span></span><span> <span>// Remove it from the cart by un-setting it </span></span><span> <span>unset( WC()->cart->cart_contents[$prod_unique_id] ); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> </span><span> <span>} </span></span><span><span>}</span></span>
The next step is to listen for the button to be clicked so that when it is clicked, we clear the cart. For that, we are going to hook into the template_redirect action.
<span><span><?php </span></span><span><span>add_action( 'woocommerce_proceed_to_checkout', 'insert_empty_cart_button' ); </span></span><span><span>function insert_empty_cart_button() { </span></span><span> <span>// Echo our Empty Cart button </span></span><span> <span>echo '<input type="submit" name="empty_cart" value="Empty Cart" />'; </span></span><span><span>}</span></span>
You’ll notice now that after pressing the button, the cart-empty.php is displayed instead of the regular template.

Now that we’ve established how to add or remove a product from the cart, even emptying the cart completely, let’s move on to building our real world scenario where knowing this kind of stuff makes a big difference.
Incentive Products
In our real world scenario, we’re going to put all of this to work by building a system where you could give away a product as an incentive to all of your customers. Well, not exactly to all of your customers, just those who qualify based on a specific requirement.
The Problem
We need to be able to give out a product of your choice as an incentive to your customers.
The Solution
Build a system which will allow you to give away your incentive product based on the following:
Having a specific product in the cart
Having a minimum total amount for your order
Having a minimum weight in your cart
Having a product from a specific category
Because we are going to be building this the right way, not only will you be able to give away the product for customer qualifying to one of these criteria, but you’ll also be able to mix these up and really narrow down who gets the product and who doesn’t.
Not only will you be able to offer your customers the incentive product by qualifying to one of those criteria, you’ll have the power to combine them. In order words, for example, you’ll be able to test for someone having at least $100 total in their cart and a product from the ‘Clothing’ category.
Let’s take a quick look at the functions we’ll be writing in a minute and what each does in our problem/solution scenario.
get_id_from_product( $product, $check_variations = true ) – Gets the product ID and returns it. Takes variation IDs into account so we check for these before checking for the actual Product ID.
qualifies_basedon_specific_product( $product_required ) – Checks whether or not a customer qualifies for the incentive by having the specified product ID as one of the items in the cart.
qualifies_basedon_weight( $weight_required ) – Checks whether or not a customer qualifies for the incentive by having a minimum weight in the cart.
qualifies_basedon_cart_total( $total_required ) – Checks whether or not the customer qualifies for the incentive by having a minimum total amount before taxes are calculated.
qualifies_basedon_product_category( $category ) – Checks whether or not the customer qualifies for the incentive by having a product from a certain category in the cart.
add_incentive_to_cart( $product_id ) – Adds the incentive product to the cart if the customer qualified for it
remove_incentive_from_cart( $product_id ) – Removes the incentive product to the cart if the customer failed to qualify for the product.
qualifies_for_incentive() – This is where the magic will happen because it will have the rules that need to be matched in order for the customer to qualify for the incentive. This function will handle the logic for our incentive program.
<span><span><?php </span></span><span><span>// Takes the Product ID and the Quantity </span></span><span><span>WC()->cart->add_to_cart( 73, 1 );</span></span>
As you can see, these functions return ‘True’ or ‘False’ so it’s going to make it really easy for us to mix it up and create an incentive program that is really flexible. What’s left to do now is come up with the rules you want to set for your customers to qualify for the incentive product and write the qualifies_for_incentive() function which will be tied to the woocommerce_check_cart_items WooCommerce action.
<span><span><?php </span></span><span><span>// template_redirect runs once for every page so you'll be </span></span><span><span>// increasing the quantity by one on every page load </span></span><span><span>add_action( 'template_redirect', 'add_random_product' ); </span></span><span><span>function add_random_product() { </span></span><span> <span>WC()->cart->add_to_cart( 73, 1 ); </span></span><span><span>}</span></span>
Below are some examples of how you can use these functions to create something really unique.
Only One Requirement
Here are a few examples setting only one requirement.
Specific Product Existing in the Cart
<span><span><?php </span></span><span><span>// Takes the Product ID and the Quantity </span></span><span><span>WC()->cart->add_to_cart( 73, 1 );</span></span>
Minimum Weight of All the Products in the Cart
<span><span><?php </span></span><span><span>// template_redirect runs once for every page so you'll be </span></span><span><span>// increasing the quantity by one on every page load </span></span><span><span>add_action( 'template_redirect', 'add_random_product' ); </span></span><span><span>function add_random_product() { </span></span><span> <span>WC()->cart->add_to_cart( 73, 1 ); </span></span><span><span>}</span></span>
Cart’s Total Excluding Taxes
<span><span><?php </span></span><span><span>add_action( 'template_redirect', 'remove_product_from_cart' ); </span></span><span><span>function remove_product_from_cart() { </span></span><span> <span>// Run only in the Cart or Checkout Page </span></span><span> <span>if( is_cart() || is_checkout() ) { </span></span><span> <span>// Set the product ID to remove </span></span><span> <span>$prod_to_remove = 56; </span></span><span> </span><span> <span>// Cycle through each product in the cart </span></span><span> <span>foreach( WC()->cart->cart_contents as $prod_in_cart ) { </span></span><span> <span>// Get the Variation or Product ID </span></span><span> <span>$prod_id = ( isset( $prod_in_cart['variation_id'] ) && $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id']; </span></span><span> </span><span> <span>// Check to see if IDs match </span></span><span> <span>if( $prod_to_remove == $prod_id ) { </span></span><span> <span>// Get it's unique ID within the Cart </span></span><span> <span>$prod_unique_id = WC()->cart->generate_cart_id( $prod_id ); </span></span><span> <span>// Remove it from the cart by un-setting it </span></span><span> <span>unset( WC()->cart->cart_contents[$prod_unique_id] ); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> </span><span> <span>} </span></span><span><span>}</span></span>
Product from a Category in the Cart
<span><span><?php </span></span><span><span>add_action( 'woocommerce_proceed_to_checkout', 'insert_empty_cart_button' ); </span></span><span><span>function insert_empty_cart_button() { </span></span><span> <span>// Echo our Empty Cart button </span></span><span> <span>echo '<input type="submit" name="empty_cart" value="Empty Cart" />'; </span></span><span><span>}</span></span>
Mixing It up
Since we have a very flexible codebase, you can mix it up and truly make your incentive program unique. Below are some more examples showing how easy it is to add more conditions as necessary.
Product from a Category in the Cart or Minimum Cart Total
<span><span><?php </span></span><span><span>// Let's wait for the button to be clicked on </span></span><span><span>add_action( 'template_redirect', 'empty_cart_button_handler' ); </span></span><span><span>function empty_cart_button_handler() { </span></span><span> <span>if( isset( $_POST['empty_cart'] ) && $_SERVER['REQUEST_METHOD'] == "POST" ) { </span></span><span> <span>WC()->cart->empty_cart( true ); </span></span><span> <span>} </span></span><span><span>}</span></span>
Product from a Category and Minimum Cart Total
<span><span><?php </span></span><span><span>/** </span></span><span><span> * Will extract the Variation ID if available otherwise it will get the Product ID </span></span><span><span> * <span>@param $product Product </span></span></span><span><span> * <span>@param <span>bool</span> $check_variations Whether or not to check for variation IDs </span></span></span><span><span> * <span>@return <span>mixed</span> </span></span></span><span><span> */ </span></span><span><span>function get_id_from_product( $product, $check_variations = true ) { </span></span><span> <span>// Are we taking variations into account? </span></span><span> <span>if( $check_variations ) { </span></span><span> <span>// Ternary Operator </span></span><span> <span>// http://php.net/manual/en/language.operators.comparison.php </span></span><span> <span>return ( isset( $product['variation_id'] ) </span></span><span> <span>&& ! empty( $product['variation_id']) </span></span><span> <span>&& $product['variation_id'] != 0 ) </span></span><span> <span>? $product['variation_id'] </span></span><span> <span>: $product['product_id']; </span></span><span> <span>} else { </span></span><span> <span>// No variations, just need the product IDs </span></span><span> <span>return $product['product_id']; </span></span><span> <span>} </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Checks the existence of a specific product in the cart </span></span><span><span> * <span>@param $product_required The Product ID required to be in the cart </span></span></span><span><span> * <span>@return <span>bool</span> </span></span></span><span><span> */ </span></span><span><span>function qualifies_basedon_specific_product( $product_required ) { </span></span><span> <span>/* </span></span><span><span> * We only want to run this on the cart or checkout page </span></span><span><span> */ </span></span><span> <span>if( is_cart() || is_checkout () ) { </span></span><span> <span>foreach( WC()->cart->cart_contents as $key => $product_in_cart ) { </span></span><span> <span>if( $product_required == get_id_from_product( $product_in_cart ) ) { </span></span><span> <span>return true; </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>// Return false in case anything fails </span></span><span> <span>return false; </span></span><span> <span>} </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Checks the cart for the weight required to qualify for the incentive </span></span><span><span> * <span>@param $weight_required Weight Required </span></span></span><span><span> * <span>@return <span>bool</span> </span></span></span><span><span> */ </span></span><span><span>function qualifies_basedon_weight( $weight_required ) { </span></span><span> </span><span> <span>/* </span></span><span><span> * We only want to run this on the cart or checkout page </span></span><span><span> */ </span></span><span> <span>if( is_cart() || is_checkout () ) { </span></span><span> <span>if( $weight_required >= WC()->cart->cart_contents_weight ) { </span></span><span> <span>return true; </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>// Return false in case anything fails </span></span><span> <span>return false; </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Checks the cart for the Total excluding taxes </span></span><span><span> * <span>@param $total_required </span></span></span><span><span> * <span>@return <span>bool</span> </span></span></span><span><span> */ </span></span><span><span>function qualifies_basedon_cart_total( $total_required ) { </span></span><span> <span>/* </span></span><span><span> * We only want to run this on the cart or checkout page </span></span><span><span> */ </span></span><span> <span>if( is_cart() || is_checkout () ) { </span></span><span> <span>if( WC()->cart->subtotal_ex_tax >= $total_required ) { </span></span><span> <span>return true; </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>// Return false in case anything fails </span></span><span> <span>return false; </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Checks the cart to verify whether or not a product from a Category is in the cart </span></span><span><span> * <span>@param $category Accepts the Product Category Name, ID, Slug or array of them </span></span></span><span><span> * <span>@return <span>bool</span> </span></span></span><span><span> */ </span></span><span><span>function qualifies_basedon_product_category( $category ) { </span></span><span> <span>foreach( WC()->cart->cart_contents as $key => $product_in_cart ) { </span></span><span> <span>if( has_term( $category, 'product_cat', get_id_from_product( $product_in_cart, false ) ) ) { </span></span><span> <span>return true; </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>// Return false in case anything fails </span></span><span> <span>return false; </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Adds a specific product to the cart </span></span><span><span> * <span>@param $product_id Product to be added to the cart </span></span></span><span><span> */ </span></span><span><span>function add_incentive_to_cart( $product_id ) { </span></span><span> <span>// Check the cart for this product </span></span><span> <span>$cart_id = WC()->cart->generate_cart_id( $product_id ); </span></span><span> <span>$prod_in_cart = WC()->cart->find_product_in_cart( $cart_id ); </span></span><span> <span>// Add the product only if it's not in the cart already </span></span><span> <span>if( ! $prod_in_cart ) { </span></span><span> <span>WC()->cart->add_to_cart( $product_id ); </span></span><span> <span>} </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Removes a specific product from the cart </span></span><span><span> * <span>@param $product_id Product ID to be removed from the cart </span></span></span><span><span> */ </span></span><span><span>function remove_incentive_from_cart( $product_id ) { </span></span><span> <span>$prod_unique_id = WC()->cart->generate_cart_id( $product_id ); </span></span><span> <span>// Remove it from the cart by un-setting it </span></span><span> <span>unset( WC()->cart->cart_contents[$prod_unique_id] ); </span></span><span><span>}</span></span>
You can even get more advanced than that and create more complex scenarios. The next step for you would be to turn this into a ‘Class’ so that you can have more than one incentive program, each with it’s own unique set of rules for qualifying.
That’s it for this article. In the third part of this series we will be working with actions and filters that run on the New Product/Edit Product screens. We’ll then explore how to add custom fields to the ‘Product Screens’ using nothing but the API.
Frequently Asked Questions (FAQs) about WooCommerce Actions and Filters
What is the difference between WooCommerce actions and filters?
Actions and filters are two types of hooks in WooCommerce. Actions allow you to add or change functionality, such as adding a new section to your website or modifying the checkout process. Filters, on the other hand, allow you to modify data within WooCommerce. For example, you can use a filter to change the price of a product or modify the text of a button.
How can I add a custom field to the WooCommerce cart?
To add a custom field to the WooCommerce cart, you can use the ‘woocommerce_cart_item_data’ filter. This filter allows you to add custom data to the cart item. You can then use the ‘woocommerce_get_item_data’ filter to display this custom data in the cart.
How can I modify the WooCommerce checkout process?
The checkout process in WooCommerce can be modified using various actions and filters. For example, you can use the ‘woocommerce_checkout_fields’ filter to modify the checkout fields, or the ‘woocommerce_checkout_process’ action to add custom validation to the checkout process.
Can I use hooks to modify WooCommerce emails?
Yes, WooCommerce provides several hooks that allow you to modify the emails sent by WooCommerce. For example, you can use the ‘woocommerce_email_header’ and ‘woocommerce_email_footer’ actions to modify the header and footer of the emails, or the ‘woocommerce_email_order_details’ action to modify the order details included in the emails.
How can I change the text of a button in WooCommerce?
To change the text of a button in WooCommerce, you can use the ‘woocommerce_order_button_text’ filter. This filter allows you to modify the text of the order button on the checkout page.
How can I add a custom message to the WooCommerce cart page?
You can add a custom message to the WooCommerce cart page using the ‘woocommerce_before_cart’ action. This action allows you to add custom content before the cart contents.
Can I use hooks to modify the WooCommerce product page?
Yes, WooCommerce provides several hooks that allow you to modify the product page. For example, you can use the ‘woocommerce_before_single_product_summary’ action to add custom content before the product summary, or the ‘woocommerce_after_single_product_summary’ action to add custom content after the product summary.
How can I modify the WooCommerce order details?
To modify the order details in WooCommerce, you can use the ‘woocommerce_order_details_after_order_table’ action. This action allows you to add custom content after the order table on the order details page.
Can I use hooks to add custom fields to the WooCommerce checkout page?
Yes, you can use the ‘woocommerce_checkout_fields’ filter to add custom fields to the checkout page in WooCommerce. This filter allows you to modify the checkout fields, including adding new fields.
How can I change the price of a product in WooCommerce using hooks?
To change the price of a product in WooCommerce, you can use the ‘woocommerce_get_price_html’ filter. This filter allows you to modify the price HTML, which includes the price of the product.
The above is the detailed content of WooCommerce Actions and Filters to Manipulate the Cart. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo(); function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.
