How To Add Quantity Input In Shop Page

Introduction

  1. This tutorial will teach you how to add a quantity input text box with the number type for each product in the shop page
  2. Something like this
Product quantity counter
  1. When a user clicks the add to cart ajax button instead of adding one quantity of the product it will add the quantity present in the input box to the cart part page

Rendering Input Quantity Box

  1. To render the quantity input box we are using the filter woocommerce_loop_add_to_cart_link
  2. You can find the official WooCommerce source code in GitHub where the filter hook is created
  3. Here is the code snippet for rendering the quantity box just above the add to cart button
  1. Lets we see line by line what this little function doing
  2. Line 1: hooking our quantity input rendering function to the filter hook with default priority 10 and the last argument passed for the function add_filter is about how many arguments the filter expects
  3. Line 3: here we declared our filter hook function with woocommerce_loop_add_to_cart_link expected two arguments $html and $product
    1. The $html argument holds the HTML of the ajax add to cart button
    2. The $product argument holds the product’s WooCommerce PHP object of any one of the following WC_Product_Simple or WC_Product_Variable or WC_Product_Grouped or WC_Product_External
    3. Learn more about all product types in the official documentation
  4. Line 6: we do a short circuit conditional check and add input quantity to only satisfying products
  5. Let’s explore each condition
    1. The first condition is $product which just check the variable’s value if it’s null or false or zero or empty string then discard the inner block of the if condition
    2. The second condition is $product->is_type('simple') which checks the current iterated product is of a type simple
    3. The third condition is $product->is_purchasable() which checks whether the product is a purchasable one
    4. The fourth condition is $product->is_in_stock() which checks whether the product is available in the stock
    5. The fifth condition is !$product->is_sold_individually() which checks negation of whether the product is sold individually without any quantities
  6. If all the above-mentioned condition is true then quantity input is rendered as in Line 7 using the WooCommerce template function woocommerce_quantity_input(array(), $product)
    1. This template function woocommerce_quantity_input accepts three optional parameters
    2. The first parameter is arguments for the HTML input number we pass an empty array so use the default values
    3. The second parameter accepts either WC_Product object or null, the default value is null
    4. If the second parameter is null then it fetches the product object from the $GLOBALS array but here we passed looped product object variable $product even though it’s not necessary to pass because the filter woocommerce_loop_add_to_cart_link assigns the current product to the $GLOBALS array
    5. The third boolean parameter by default accepts true, if true it echoes the HTML else return the HTML
  7. Line 9: returns the add to cart button HTML
  8. Now we completely explored quantity input HTML rendering functionality next we will see quantity updating plain JavaScript function

Quantity Updating Functionality

  1. We hooked our function to the hook action wp_footer which prints the JS data or scripts just before the closing body tag
  2. You can find the official WordPress source code in GitHub where the action hook is created
  3. Here is the code snippet for updating the quantity data attribute of the add to cart button when the user updates the input quantity
  1. Inspect the add to cart button after adding this function you will see the quantity is updated with the value present in the quantity input box
  1. Let’s explore the frontend part functionality which is hooked to the action wp_footer
  2. Line 2: we hooked our frontend function update_quantity_attribute to the action hook wp_footer
  3. Line 3: declared the frontend function
  4. Line 6: opened the script tag
  5. Line 7: declared a JS variable simpleProductInput and assigned a DOM node list which we fetched using the JS method querySelectorAll of the document object
  6. Let us explore the string parameter '.product-type-simple .quantity > input' passed to the method querySelectorAll
    1. The method querySelectorAll behaves just like CSS selector so whatever DOM matched to the argument passed to the method is fetched as JS node list
    2. .product-type-simple is the class selector which fetches the DOM element which has the class product-type-simple
    3. If we further extend our selector like .product-type-simple .quantity which fetches the element matches with class value quantity and present inside the element with the class value product-type-simple
    4. The angle bracket > denotes child combinator selector which means it selects only direct children element
    5. input selects the dom element with HTML tag input
    6. So what our selector .product-type-simple .quantity > input is doing?
    7. It selects the input DOM present in each simple product
  7. Line 9: loop and fetch every targeted dom node from the dom node list
  8. Line 10: the method dom.addEventListener accepts two parameters
  9. The first one is to bind/add an event input it’s just like the events click, change, etc. to each input tag and the second parameter is listener anonymous function
  10. Let’s see the inner working of the anonymous function which accepts a single argument Event object e
    1. Inside the anonymous function, we chained a sequence of methods which is called as method chaining
    2. e.target.parentElement.nextElementSibling.setAttribute('data-quantity', e.target.value)
    3. e.target property points to DOM object which triggers the current event here it is the quantity input box
    4. e.target.parentElement returns the parent element of the target which is HTML div rendered over the quantity input tag
    5. e.target.parentElement.nextElementSibling returns the next element which sibling to the targeted DOM
    6. Closely note here we used nextElementSibling instead of nextSibling because the nextSibling fetches immediate next node it may be an element node or text node or comment node but nextElementSibling fetches the element node like P, Div, Span, etc. here we fetch anchor tag of the add to cart button
    7. Finally, we set the quantity what present in the input tag to the anchor tag add to cart button data attribute using the method setAttribute('data-quantity', e.target.value)
    8. Which accepts two parameters, the first one is the name of the attribute data-quantity and the second one is the value assigned to that attribute
    9. Here the value is quantity input’s value because it is the target of the current event
  11. That’s all finally we enclose the script and function

Conclusion

  1. In this tutorial, you learned how to intercept the shop page’s product loop and insert our desired logic or HTML
  2. Learned about types of product object such as WC_Product_Simple, WC_Product_Variable, WC_Product_Grouped and WC_Product_External
  3. Learned about product object methods such as is_type, is_purchasable, is_in_stock and is_sold_individually
  4. Learned about woocommerce_quantity_input which return or echo HTML of the quantity input
  5. Learned about Javascript event, method chaining, CSS selector and update or override the HTML attributes
  6. We implemented the functionality to add desired quantity instead of adding a single quantity in the cart

Comments

2 responses to “How To Add Quantity Input In Shop Page”

  1. I am sure this paragraph has touched all the internet users,
    its really really fastidious post on building up new blog.
    I’ll immediately clutch your rss feed as I can not in finding your e-mail subscription hyperlink or e-newsletter
    service. Do you’ve any? Please let me know in order that I could subscribe.
    Thanks. Greetings from Los angeles! I’m bored to tears at work
    so I decided to check out your website on my
    iphone during lunch break. I enjoy the information you present
    here and can’t wait to take a look when I get home.

    I’m amazed at how quick your blog loaded on my cell phone ..
    I’m not even using WIFI, just 3G .. Anyways,
    superb site! http://cars.com

    Also visit my web page :: Jack

    1. Jack,

      Thanks for your interest in my blogging. There is no newsletter subscription intentionally developed my website as minimal as possible with security in mind. Thank you for your appreciation. I always post a topic/month. I hope I’m not bored you by filling your mind full of programming thingy!!!

      Here is the RSS feed: https://www.vijayan.in/feed/