最快的方法:计算WooCommerce中的所有产品(包括变体)

I'm wondering if there exist any faster approaches to count all products in WooCommerce (and their child-variations), than this following code-example:

function total_product_count() {
    $product_count = 0;

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1
    );

    /* Initialize WP_Query, and retrieve all product-pages */
    $loop = new WP_Query($args);

    /* Check if array contains any posts */
    if ($loop->have_posts()): 
        while ($loop->have_posts()): 
            $loop->the_post();
            global $product;

            /* Count the children - add count to product_count */
            product_count += count($product->get_children());

        endwhile;

    endif;

    return $product_count;
}

On my local XAMPP web-server the function executes in 3 seconds (having 253 products), which is way too long time. The function returns 1269.

as your naming

$loop =new WP_Query($args);

try this code

$loop->post_count;
 while ($loop->have_posts()){
   global $product;
   /* Count the children - add count to product_count */
    $loop->post_count += count($product->get_children());

 }

WP_Query has a property which gives you the number of posts found matching the current query parameters:

function total_product_count() {
    $args = array( 'post_type' => 'product', 'posts_per_page' => -1 );

    $products = new WP_Query( $args );

    return $products->found_posts;
}