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



我想知道是否存在任何更快的方法来计算WooCommerce中的所有产品(及其子变量),而不是以下代码示例:

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;
}

在我本地的XAMPP web服务器上,该函数在3秒内执行(有253个产品),这是太长时间了。函数返回1269

$product->get_children()在这种情况下并不总是正确的。get_children()返回子产品和分组产品(如果存在)。

我希望更好和最快的方法是使用wpdb:: MySQL查询方法。试试下面的代码

echo 'Number of main products => '.main_product_count();
echo 'Number of variations => '. variation_product_count();
function main_product_count() {
    global $wpdb;
    $count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE `post_type` LIKE 'product'");
    return $count;
}
function variation_product_count() {
    global $wpdb;
    $count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE `post_type` LIKE 'product_variation'");
    return $count;
}

作为你的命名

$loop =new WP_Query($args);

试试这个代码

$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有一个属性,它给你找到匹配当前查询参数的帖子的数量:

function total_product_count() {
    $args = array( 'post_type' => 'product', 'posts_per_page' => -1 );
    $products = new WP_Query( $args );
    return $products->found_posts;
}

最新更新