WooCommerce 产品收集问题

WooCommerce product collection issue

我想问一下,当我在旧的 woocommerce 版本的电子商店中有 3000 个可变产品时,当我试图遍历它们时,我在 return 中只得到 300 个。

我使用以下代码来生成产品提要。

$args = array( 'post_type' => 'product');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();

可变产品也被称为可变的,因为据我所知,它们支持变化。这意味着 3000 个可变产品不是 3000 个 "normal" 个产品,而是我看到的 300 个是正确的数量吗?

可能您混淆了产品(简单或可变)和产品变体(保留给可变产品)...您需要在 WP_Query 中显示产品(简单和可变),但不需要您的产品变体。

使用'post_type' => 'product',您将同时获得简单和可变的产品。

缺少的参数是 posts_per_page,要设置为 -1

因此您的代码将是:

$args = array( 'post_type' => 'product', 'posts_per_page' => -1);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) :
    $loop->the_post();
    // set all product IDs in an array
    $all_product_ids[] = $loop->post->ID;
endwhile;

// Testing: Output the number of products in that query
echo '<p>Products count: ' . count($all_product_ids) . '</p>';

然后您将获得所有产品。


也许您可以尝试使用 WPDB 查询:

## --- THE SQL QUERY --- ##

global $wpdb;

$table_name = $wpdb->prefix . "posts";

$product_ids_array = $wpdb->get_col("
    SELECT `ID`
    FROM `$table_name`
    WHERE `post_status` LIKE 'publish'
    AND `post_type` LIKE 'product'
");

## --- TESTING OUTPUT --- ##

// Testing raw output of product IDs
print_r($product_ids_arr);

// Number of products
$products_count = count($product_ids_arr);
echo '<p>Products count: '. $products_count. '</p>';

## --- THE LOOP --- ##

foreach ($product_ids_array as $product_id):

    // Get an instance of WP_Product object 
    $product = new WC_Product($product_id);

    // Use the WP_Product methods to get and output the necessary data

endforeach;