【问题标题】:WooCommerce get all products with SKUWooCommerce 使用 SKU 获取所有产品
【发布时间】:2021-02-22 09:02:42
【问题描述】:

我想用这个代码获取一个带有 sku 和 post id 的产品列表,这个代码看起来一切都很好:

$statuses = array('publish', 'draft');

// Args on the main query for WC_Product_Query
$args = [
    'status'    => $statuses,
    'orderby'   => 'name',
    'order'     => 'ASC',
    'limit'     => -1,
];

$vendor_products = wc_get_products($args);

$list_array = array();

foreach ($vendor_products as $key => $product) {

    if ($product->get_type() == "variable") {

        // Args on product variations query for a variable product using a WP_Query
        $args2 = array( 
            'post_parent' => $product->get_id(), 
            'post_type'   => 'product_variation', 
            'orderby'     => array( 'menu_order' => 'ASC', 'ID' => 'ASC' ), 
            'fields'      => 'ids', 
            'numberposts' => -1, 
        ); 

        foreach ( get_posts( $args2 ) as $child_id ) {
            // get an instance of the WC_Variation_product Object
            $variation = wc_get_product( $child_id ); 

            if ( ! $variation || ! $variation->exists() ) {
                continue;
            }

            $list_array[] = array(
                'sku'      => $variation->get_sku(),
                'postid'   => $variation->get_id()
            );
        }

    } else {

        $list_array[] = array(
            'sku'      => $product->get_sku(),
            'postid'   => $product->get_id()
        );

    }
}

我总共有 1660 个(470 个已发布和 1,190 个草稿)产品,但它只返回 501 个产品,我不知道为什么! 这是我在 woocommerce 中的产品:

这是查询的最终结果:

这是 Janki 代码的结果

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案1】:
        // Woocommerce get all products
    $args = array(
        'post_type'  => array('product','product_variation'),
        'meta_key'   => '_sku',
        'post_status' => array('publish','draft'), 
        'meta_query' => array(
            array(
                'key'     => '_sku',
                'compare' => 'EXISTS',
            ),
        ),
    );
           
    $products = new WP_Query($args);
     
        /* using this code you can get all products */
        /* this may help you to get details */
    

    【讨论】:

    • 此代码有效,但我需要产品和产品变体的 SKU,我不知道如何获取它们
    • 我已经更新了代码,请你试试这个来解决你的问题
    • 谢谢,'post_type' => ''product_variation',',只有 ??这是对的吗?
    • post_type 只是 product_variation ,这段代码是否给了我产品和产品变体?
    • 数组也可以用于多种类型
    猜你喜欢
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多