繁体   English   中英

在 Woocommerce 3 中以编程方式设置产品销售价格和购物车项目价格

[英]Set programmatically product sale price and cart item prices in Woocommerce 3

这是继续: 在 WooCommerce 3 中以编程方式设置产品销售价格

答案是有效的,但是一旦用户将产品添加到购物车,结帐时仍会显示旧价格。

如何在购物车和结帐页面上获得购物车商品的正确销售价格?

任何帮助表示赞赏。

让它适用于购物车和结账页面(以及订单和电子邮件通知)的缺失部分是一个非常简单的技巧:

add_action( 'woocommerce_before_calculate_totals', 'set_cart_item_sale_price', 20, 1 );
function set_cart_item_sale_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

    // Iterate through each cart item
    foreach( $cart->get_cart() as $cart_item ) {
        $price = $cart_item['data']->get_sale_price(); // get sale price
        $cart_item['data']->set_price( $price ); // Set the sale price

    }
}

代码位于活动子主题(活动主题)的 function.php 文件中。

测试和工作。

所以代码只是将产品销售价格设置为购物车项目中的产品价格并且它可以工作。

@LoicTheAztec 答案非常有效,但不是必需的。

您至少需要使用 dynamic_sales_price_function 过滤woocommerce_product_get_pricewoocommerce_product_variation_get_price

为了让它真正顺畅地工作,您还需要更多的过滤器。

接受的答案对我不起作用。 这是有效的:

function get_active_price($price, $product) {
        if ($product->is_on_sale()) {
            return $product->get_sale_price();
        }
        return $product->get_regular_price();
    }

add_filter('woocommerce_product_get_price', 'get_active_price'));

这适用于定制销售和正常价格。

希望此代码对您有所帮助

add_filter( 'woocommerce_get_price_html', 'bbloomer_alter_price_display', 9999, 2 );

function bbloomer_alter_price_display( $price_html, $product ) {

  // ONLY ON FRONTEND
  if ( is_admin() ) return $price_html;

  // ONLY IF PRICE NOT NULL
  if ( '' === $product->get_price() ) return $price_html;

  // IF CUSTOMER LOGGED IN, APPLY 20% DISCOUNT   
  if ( wc_current_user_has_role( 'customer' ) ) {
    $orig_price = wc_get_price_to_display( $product );
    $price_html = wc_price( $orig_price * 0.80 );
  }
  return $price_html;
}

add_action( 'woocommerce_before_calculate_totals', 'bbloomer_alter_price_cart', 9999 );

function bbloomer_alter_price_cart( $cart ) {

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

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

  // IF CUSTOMER NOT LOGGED IN, DONT APPLY DISCOUNT
  if ( ! wc_current_user_has_role( 'customer' ) ) return;

  // LOOP THROUGH CART ITEMS & APPLY 20% DISCOUNT
  foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
    $product = $cart_item['data'];
    $price = $product->get_price();
    $cart_item['data']->set_price( $price * 0.80 );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM