wordpress - WooCommerce 使用 SKU 获取所有产品
问题描述
我想使用此代码获取带有 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 中的产品:
解决方案
// 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 */
推荐阅读
- javascript - wait() 找不到以前触发的别名路由
- android - 我必须在 5x3 的网格中插入随机黑色,每行应该只包含一个黑色单元格
- perl - 如何在没有终端访问权限的情况下使用 Perl 模块?
- ruby-on-rails - 只有在 Rails.application.routes.url_helpers 存在路由时才链接到路径
- c# - 实体框架无法创建任何迁移
- python - 如何使用 matplotlib 在 python 中绘制 tensorflow mfcc
- ios - Swift核心数据谓词问题
- php - Laravel 将行从一个数据表复制到另一个数据表
- xamarin - 未使用 cloudrail 库 xamarin.ios 连接到 Google 驱动器
- apache2 - 别名 proxypass 优先级如何工作?