簡體   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