
List the stock numbers for each product and variation.
I am working on a project where the client will scan barcodes to increment their stock levels. The first part of this involved creating a page listing the stock level of every product and variation.
Incremental development
Instead of jumping into writing the full code I worked on it bit by bit. I learned about the various combinations of product setup that I would likely encounter – simple and variable products and those with and without managed stock.
I started with a standalone script and created a single product object (using wc_get_product() with the ID of a simple product). With the object I checked whether its stock was managed ($product->get_manage_stock()) and then the amount of stock available ($product->get_stock_quantity()). For fun I checked the stock status, whether it was in stock or out of stock or on back order ($product->get_stock_status()).
Next I worked on the same information for a variable product. The first step here is to get all the variations ($product->get_available_variations()) and then call wc_get_product() on each one. After that it’s the same.
With both those product types sorted I added a call to wc_get_products() (note the plural) and looped through each product and displayed the retrieved information. It was looking good.
Add Dashboard page
Continuing the development incrementally, I then added code to display the stock level info as a page in the Dashboard. This allowed me secure the page as it would require the shop manager to login to view it.
I added a plugin header comment to the PHP file to change it from a standalone script to a plugin and added a add_submenu_page() call to put the new page in the WooCommerce area.
To add some structure to the information I put it into a table. I considered using the WP_List_Table class but decided to keep the code simple. I did however copy some of the CSS classes from it to get the familiar styles.
After that was working I combined into functions the code that was common to the simple and variable products. These functions created the html markup so that’s now easier to maintain.
Finally, I added a few small enhancements to highlight issues like low stock levels (using the wc_get_low_stock_amount() function to get the stock amount number) and when a product’s stock is not managed.

Leave a Reply