In this video I’ll show you how to add an additional piece of social proof to your WooCommerce single product pages.
Social proof show that other people believe enough in your products to buy them, we are adding a
Video
Explanation:
- Function Definition:
display_product_purchase_count()
: This function retrieves all orders with specific statuses (completed, processing, on-hold) and counts the total quantity of the current product ordered across all orders.
- Global Product Object:
global $product;
: Accesses the global product object for the current product page.
- Order Arguments:
$args
: Defines the criteria for fetching orders.wc_get_orders( $args )
retrieves orders based on the defined criteria.
- Loop Through Orders:
- Loops through each order and its items, checking if the product ID matches the current product’s ID. If it matches, the quantity ordered is added to the
$order_count
.
- Loops through each order and its items, checking if the product ID matches the current product’s ID. If it matches, the quantity ordered is added to the
- Display Purchase Count:
- The purchase count is displayed before the “Add to Cart” button using
echo
within a<p>
tag.
- The purchase count is displayed before the “Add to Cart” button using
- Hook into WooCommerce:
add_action( 'woocommerce_single_product_summary', 'display_product_purchase_count', 25 );
: Hooks the function into the WooCommerce single product summary with a priority of 25, ensuring it appears before the “Add to Cart” button.
Adding the Code:
- Open Your Theme’s
functions.php
File:- Go to your WordPress dashboard.
- Navigate to
Appearance > Theme Editor
. - Select your theme’s
functions.php
file from the right-hand side.
- Add the Code:
- Copy the above code snippet and paste it at the end of the
functions.php
file. - Save the changes.
- Copy the above code snippet and paste it at the end of the
Result:
When you view a product page on your WooCommerce site, you should now see the number of times the product has been purchased displayed above the “Add to Cart” button.
Note: This code retrieves all orders, which might be resource-intensive on sites with a large number of orders. For better performance on high-traffic sites, consider using more efficient methods or caching the results. I’ll cover how to cache data like this in my next video.
Wrap UP
If you need help adding social proof to your WooCommerce store please visit the work with me page for details.