Show the quantity of each Product ordered in a WooCommerce Order

In the tutorial https://toolset.com/learn/create-an-ecommerce-wordpress-site/displaying-more-information-from-woocommerce/how-to-display-woocommerce-orders-on-the-front-end/#how-to-display-ordered-products-when-listing-orders it shows how to list all the Products associated with a WooCommerce Order. We will extend this to add the requested quantity of each Product.

First, add the following custom shortcode to your child theme’s functions.php file:

function order_product_qty_func($atts) {
  $a = shortcode_atts( array(
      'orderid' => '',
      'productid' => ''
  ), $atts );

  // get the order using the orderid shortcode attribute
  $order = wc_get_order( $a['orderid'] );

  // loop over the order items
  foreach ($order->get_items() as $item_id => $item_data) {

    // Get an instance of corresponding the WC_Product object
    $product = $item_data->get_product();
    $product_id = $product->get_id();

    // if the product id matches the current product id in the loop, return the quantity
    if( $product_id == $a['productid'] )
      return $item_data->get_quantity();
  }
  return;
}

add_shortcode( 'order_product_qty', 'order_product_qty_func');

This shortcode accepts two parameters: orderid and productid. We must place this shortcode in a View of Ordered Products, so we need to be able to access both these values in that View. The Product ID is easy – it’s just the post ID of the current post in the loop. The Order ID is not so easy. We need to access that information from the View of Orders. We can do that by adding it as a shortcode attribute to the View of Ordered Products shortcode:

" orderid="7198"]

Now in the View of Ordered Products we can use the custom shortcode like this:

[order_product_qty productid="7198" orderid=""][/order_product_qty]

 


Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments