使用WC_Variable_Product
get_visible_children()
(或get_children()
)方法,尝试:
global $product; // If needed | or $product = wc_get_product( $product_id );
if( $product->is_type( 'variable' ) ){
foreach ( $product->get_visible_children() as $variation_id ) {
$variation = wc_get_product( $variation_id ); // Get the product variation object
$weight = $variation->get_weight(); // Get weight from variation
if ( ! $weight ) {
echo '<div>' __("No weight") . '</div>';
} else {
echo '<div><strong>' __("Weight") . ':</strong> ' . wc_format_weight( $weight ) . '</div>';
}
}
}
或者你可以使用WC_Variable_Product
get_available_variations()
如下:
global $product; // If needed | or $product = wc_get_product( $product_id );
if( $product->is_type( 'variable' ) ){
foreach ( $product->get_available_variations() as $key => $variation_data ) {
$weight = $variation_data['weight']; // Get weight from variation
if ( ! $weight ) {
echo '<div>' __("No weight") . '</div>';
} else {
echo '<div><strong>' __("Weight") . ':</strong> ' . $variation_data['weight_html'] . '</div>';
}
}
}
两个代码片段都有效。