WooCommerce 使用 SKU 获取所有产品

时间:2021-02-22 09:02:42

标签: wordpress woocommerce

我想获取带有 sku 的产品列表并使用此代码发布 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 中的产品: enter image description here

这是查询的最终结果: enter image description here

这是Janki代码的结果 enter image description here

1 个答案:

答案 0 :(得分:2)

    // 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 */