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

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

这是以下内容的延续:在 WooCommerce 3 中以编程方式设置产品销售价格

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

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

如有任何帮助,我们将不胜感激。

php wordpress woocommerce cart product-price
4个回答
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 文件中。

已测试且有效。

因此,代码只需将产品销售价格设置为购物车项目中的产品价格即可。


1
投票

希望此代码对您有帮助

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 );
  }
}

0
投票

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

您需要使用dynamic_sales_price_函数至少过滤 woocommerce_product_get_pricewoocommerce_product_variation_get_price

为了使其工作真正顺利,您还需要更多过滤器。


0
投票

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

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'));

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

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