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></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></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></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></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></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></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></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></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></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></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></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></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></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!

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

WordPress is very customized, providing a wide range of flexibility and customizability. 1) Through the theme and plug-in ecosystem, 2) use RESTAPI for front-end development, 3) In-depth code level modifications, users can achieve a highly personalized experience. However, customization requires mastering technologies such as PHP, JavaScript, CSS, etc., and pay attention to performance optimization and plug-in selection to avoid potential problems.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
