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

问题描述 投票:0回答:4

我想知道是否存在比以下代码示例更快的方法来计算 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。

php wordpress woocommerce
4个回答
0
投票
在这种情况下,

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

0
投票

在 Wocomerce 中,每个变体产品在 wp_posts 表中都有一行: 所以没关系,用这个:

global $wpdb;
$query= "SELECT ID from `wp_posts` WHERE post_status='publish' AND post_type='product'";
$product_count=count($wpdb->get_results($query));

但如果您想确保每个变体都算作单独的产品,您可以使用此:

global $wpdb;
$query= "SELECT ID from `wp_posts` WHERE post_status='publish' AND post_type='product' OR post_type='product_variation' ";
$product_count=count($wpdb->get_results($query));

-1
投票

作为你的命名

$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());

 }

-1
投票

WP_Query
有一个属性,可以为您提供找到的与当前查询参数匹配的帖子数量:

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

    $products = new WP_Query( $args );

    return $products->found_posts;
}
© www.soinside.com 2019 - 2024. All rights reserved.