如何在Woocommerce-WordPress中动态更改产品的价格


How to dynamically change the price of a product in Woocommerce - WordPress?

如果我的客户来自某个特定的地方,我需要更改我商店中产品的价格,并享受10%的折扣,因此,我编写了以下代码:

add_filter('woocommerce_price_html', 'my_price_edit');
function my_price_edit() {
     $product = new WC_Product( get_the_ID() );
     $price = $product->price;
     echo $price * 0.9;
}

好的,它有效!但当在结账时,价格是正常的,没有10%的折扣!

是否有一些挂钩可以更改结账区域中产品的价格,或者有一些不同的代码可以在两者中正确更改(在产品页面和结账中)?

Wooccommerce也有新功能。你的问题看起来和这个问题很相似。在Cart&结账

我认为您需要使用woommerce_cart_item_subtotal挂钩来直接更改购物车中的价格(不完全作为参数)

我对代码做了一点修改(更改了价格公式)。我想这可能对你有帮助。

    add_filter( 'woocommerce_get_discounted_price', 'calculate_discounted_price', 10, 2 );
    // Display the line total price
    add_filter( 'woocommerce_cart_item_subtotal', 'display_discounted_price', 10, 2 );
    function calculate_discounted_price( $price, $values ) {
        // You have all your data on $values;
        $price = $price*.09;
        return $price;
    }
    // wc_price => format the price with your own currency
    function display_discounted_price( $values, $item ) {
        return wc_price( $item[ 'line_total' ] );
    }