【问题标题】:WooCommerce product collection issueWooCommerce 产品收集问题
【发布时间】:2017-12-26 06:39:44
【问题描述】:

我想问一下,当我在旧的 woocommerce 版本的 eshop 中有 3000 个可变产品时,当我尝试循环遍历它们时,我怎么可能只得到 300 个作为回报。

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

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

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

【问题讨论】:

    标签: php wordpress woocommerce product


    【解决方案1】:

    可能是您混淆了产品(简单或可变)和产品变体(仍然是可变产品)...您需要在 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;
    

    【讨论】:

    • Loic 感谢您的回答,我会检查并回复您!
    • 我按照您对我的建议尝试了更正,但输出是相同的。在后端虽然有 3000 个可变产品和 81 个简单产品。所以我想了解我做错了什么。
    • 谢谢我加了你@loictheaztec!
    猜你喜欢
    • 2023-03-05
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    相关资源
    最近更新 更多