This is a modified version of the tep_count_products_in_category function defined in includes/functions/general.php Only two queries are done to count the products of all categories and subcategories. This is the first time I write code for OSC, so I'm sure I'm failing to follow whatever standards you have in place. Maybe some more experienced developer wants to have a look at it.