If you want to figure out how products you have in your WooCommerce store programmatically you can use this WordPress function written in php.
How to Get The Total Products Using wp_count_posts() WordPress Function
wp_count_posts();
The first parameter of the function is the most important one. It is the custom post type whose posts we want counted.
Because WooCommerce stores each product as a custom post type called: product we’ll pass that as a paramter.
$count_res_obj = wp_count_posts('product);
$total_products = empty($count_res_obj->publish) ? 0 : count($count_res_obj->publish)
it’s always nice to name your variables properly so you know exactly what type of data it holds. Also we’re checking with my favorite method empty().
It does multiple things at ones. If wp_count_posts() by any chance if the function returns something that’s not object we’ll catch that with empty and won’t trigger any php notices/warnings. If there’s an error we’ll consider that we don’t have any products which is way better than showing an error.
In some cases accessing an object directly which is supposed to have another object in it could crash the site because of the main object is null.
For more info you can check the function’s documentation.
If you need to show the number of products using a shortcode you can check this github gist by Gerhard Potgieter (@kloon)
https://gist.github.com/kloon/4218605
// [product_count] shortcode
function product_count_shortcode( ) {
$count_posts = wp_count_posts( 'product' );
return $count_posts->publish;
}
add_shortcode( 'product_count', 'product_count_shortcode' );
How to Get the Total Products Using wc_get_products() WooCommerce Function
If for some reason the function above doesn’t return what you need you can also use wc_get_products() function that WooCommerce defines.
$args = [
'limit' => -1,
'return' => 'ids',
'status' => 'publish',
];
$product_ids_arr = wc_get_products($args);
$total_products = empty($product_ids_arr) ? 0 : count($product_ids_arr);
Woocommerce defines this nice function which accepts several parameters.
In the example above we query only for IDs because that will be more efficient and won’t waste memory and processing power unnecessarily.
You can check more examples how to use wc_get_products() using the link below.
https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query
You can query for different types of products such as: external (‘type’ => ‘external’) and also for different status e.g. ‘status’ => ‘draft’
Hopefully with these two functions you’ll be able to get the total number of products your WooCommerce store.