We already talked about displaying the total number of sales for a given product ID, however what if you just want to calculate sales in the last week?

This is a much better option when you have a busy WooCommerce shop and want to increase your sales conversion rate.

So, here’s the snippet – paste to your functions.php and enjoy!

Calculating recent sales (last week) and displaying them on the WooCommerce single product page

PHP Snippet: Display Number of Sales in the Last Week @ WooCommerce Single Product Page

/**
 * @snippet       Product Sales Last Week - WooCommerce Single Product Page
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.6.4
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_action( 'woocommerce_single_product_summary', 'bbloomer_product_sold_count_1_week', 11 );
 
function bbloomer_product_sold_count_1_week() {
	global $product;
	
	// GET LAST WEEK ORDERS
	$all_orders = wc_get_orders(
		array(
			'limit' => -1,
			'status' => array_map( 'wc_get_order_status_name', wc_get_is_paid_statuses() ),
			'date_after' => date( 'Y-m-d', strtotime( '-1 week' ) ),
			'return' => 'ids',
		)
	);
    
	// LOOP THROUGH ORDERS AND SUM QUANTITIES PURCHASED
	$count = 0;
	foreach ( $all_orders as $all_order ) {
		$order = wc_get_order( $all_order );
		$items = $order->get_items();
		foreach ( $items as $item ) {
			$product_id = $item->get_product_id();
			if ( $product_id == $product->get_id() ) {
				$count = $count + absint( $item['qty'] ); 
			}
		}
	}
	
	if ( $count > 0 ) echo "<p>Recent sales: $count</p>";
}
Share:

Leave a Reply