所以我有一系列产品,售价也很可观。
通常从数组获取值很简单,如下所示:
$the_sups = array(
21179 => 14.99, //shine
21169 => 17.95, //boost
1665 => 19.15, //flexx
1663 => 17.85, //revive
1661 => 19.75, //muscle
1657 => 17.85 //maximus
);
echo $the_sups[21179];
这将返回14.99
在我的一生中,当通过 woocommerce_before_calculate_totals
NULL
返回
下面是我使用的代码,如果从数组返回价格,我知道它应该可以工作:
$sup_discount= 0.9;
$the_sups = array(
21179 => 14.99, //shine
21169 => 17.95, //boost
1665 => 19.15, //flexx
1663 => 17.85, //revive
1661 => 19.75, //muscle
1657 => 17.85 //maximus
);
foreach (WC()->cart->get_cart() as $hash => $value ) {
if( in_array( 52, $value['data']->get_category_ids() ) ) {
echo $value['product_id']; //IS 21179
$product_value = $the_sups[$value['product_id']];
var_dump($product_value); //IS ALWAYS NULL
$value['data']->set_price($product_value * $sup_discount);
}
}
有人可以解释一下我做错了什么吗?
最佳答案
这似乎可以做到,用 WooCommerce 4.1.0 进行测试
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
/* SETTINGS */
$sup_discount = 0.9;
$the_sups = array(
21179 => 14.99, // shine
21169 => 17.95, // boost
1665 => 19.15, // flexx
1663 => 17.85, // revive
1661 => 19.75, // muscle
1657 => 17.85, // maximus
);
/* END SETTINGS */
// Loop through cart items
foreach ( $cart->get_cart() as $value ) {
// Get product id
$product_id = $value['product_id'];
if( in_array( 52, $value['data']->get_category_ids() ) ) {
echo $product_id;
$product_value = $the_sups[ $product_id ];
var_dump($product_value);
$value['data']->set_price( $product_value * $sup_discount );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
关于php - 通过 woocommerce_before_calculate_totals 更改价格时获取数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61880518/