更改 Woocommerce 中特定产品类别的购物车商品价格

问题描述 投票:0回答:1

我想将购物车中产品的常规价格更改为仅限特定类别(“T 恤-d”、“袜子-d”、“慢跑者-d”、“拳击手-d”)的自定义价格,因为每个这些产品共有 2 个不同的类别。

我尝试这样做,它有效,但自定义价格也会影响其他类别,我只想显示其他类别的原始价格(“T 恤”、“袜子”、“慢跑者”、“拳击手”)。

我需要这方面的帮助。

这是迄今为止我的代码:

function changeprice($html, $cart_item, $cart_item_key){
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        //$thepro = $woocommerce->cart->get_cart();
$product = $cart_item['data'];
 $heading_nicename = array('t-shirts-d','socks-d','joggers-d','boxers-d');
 //$heading_nicename1 = array('t-shirts','socks','joggers','boxers');
   $termsother =  $heading_nicename;
 foreach( $termsother as $termsnew ) {
  if (is_cart()) {
            $price_adjusted = 666.666666667; // your adjustments here
            $price_base = $cart_item['data']->sale_price;
            if (!empty($price_adjusted)) {
                if (intval($price_adjusted) > 0) {
                    $cart_item['data']->set_price($price_adjusted);
                } /*else {
                    $html = '<span class="amount">' . wc_price($price_base) 
  . '</span>';
                }*/
            }
        }
     }
   }
   }
    add_filter('woocommerce_cart_item_price', 'changeprice', 100, 3);
php woocommerce cart custom-taxonomy product-price
1个回答
4
投票

正确的工作钩(更新)

add_action( 'woocommerce_before_calculate_totals', 'change_cart_items_prices', 10, 1 );
function change_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        if( has_term( array('t-shirts-d','socks-d','joggers-d','boxers-d'), 'product_cat', $cart_item['product_id'] ) ){
            $price_adjusted = 666.666666667; // your adjustments here
            if ( ! empty( $price_adjusted ) && intval( $price_adjusted ) > 0) {
                $cart_item['data']->set_price( $price_adjusted );
            }
        }
    }
}

代码位于活动子主题(或主题)的 function.php 文件中,或者也位于任何插件文件中。

这次购物车和结帐页面上的一切都可以正常工作。 总计也更新了

© www.soinside.com 2019 - 2024. All rights reserved.