[英]Fastest approach: Count all products (including variations) in 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 网络服务器上,该函数在 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 =新的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.