gpt4 book ai didi

php - 从可变产品的 WooCommerce 变体中获取权重值

转载 作者:行者123 更新时间:2023-12-04 08:15:51 25 4
gpt4 key购买 nike

我正在开发一个自动调整产品价格的插件。我所有的产品都是可变产品,这让我无法解决这个问题。

if( $product->is_type( 'variable' ) ){

foreach ( $product->get_available_variations() as $key => $variation ) {

foreach ($variation['attributes'] as $attribute ) {

if ( ! $attribute->get_weight() ) {
我有一个检查以确保产品是可变的。唯一的产品属性是“尺寸”。在这里,我对每个产品有 4-8 种不同的尺寸变化。每一个都有一个权重值,这似乎是 Woocommerce 默认实现的。我无法从每个变体中获得重量。好奇我是否从错误的地方调用 get_weight() ,或者是否有不同的方法。
get_weight() 当然不起作用,所以我想知道从变体中获取属性是否完全错误?

最佳答案

使用 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>';
}
}
}
两个代码片段都有效。

关于php - 从可变产品的 WooCommerce 变体中获取权重值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65708223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com