您应该更好地使用WC_Product_Variable
get_children()
以下方法:
$args = [
'status' => array('publish', 'draft'),
'orderby' => 'name',
'order' => 'ASC',
'limit' => -1,
];
$vendor_products = wc_get_products($args);
$list_array = array();
foreach ($vendor_products as $key => $product) {
if ( $product->is_type( "variable" ) ) {
foreach ( $product->get_children( false ) 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(),
'Name' => $product->get_name() . " - " . $child_id,
);
}
} else {
$list_array[] = array(
'SKU' => $product->get_sku(),
'Name' => $product->get_name(),
);
}
}
return $list_array;
甚至是其他一些可用的方法,例如(在查看其源代码时使用方法)。它应该更好地工作......get_available_variations()
get_children()
针对具有不同其他帖子状态的可变产品的产品变体而不是“ publish"
。
在这种情况下,您应该使用自定义 WP_Query 替换 get_children() 方法,该方法将处理其他帖子状态,如下所示:
$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',
'post_status' => $statuses,
'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(),
'Name' => $product->get_name() . " - " . $child_id,
);
}
} else {
$list_array[] = array(
'SKU' => $product->get_sku(),
'Name' => $product->get_name(),
);
}
}
return $list_array;
这次您将获得可变产品的所有产品变体。
供参考:Product -> Get Children 不会返回所有变体 #13469