Checkout price issue using woocommerce_product_get_price hook

依然范特西╮ 提交于 2019-12-04 04:46:31

问题


I need to double the price for every product in Woocommerce frontend. For this I used the following code:

add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
    return $price*2;
}

But there is an error using this code. checkout page price is not correct. for example the product orginal price is 10. We double the price by this code . so the product price is 20 now. When i added this product to the cart then cart and checkout page price is 40. That means this multiplication is take place in two times.

Please help to solve this.


回答1:


Updated To double the price:

1) First you will restrict your code to single product and archives pages only:

add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
    if( is_shop() || is_product_category() || is_product_tag() || is_product() )
        return $price*2;

    return $price;
}

2) Then for cart and checkout pages, you will change the cart item price this way:

add_filter( 'woocommerce_add_cart_item', 'set_custom_cart_item_prices', 20, 2 );
function set_custom_cart_item_prices( $cart_data, $cart_item_key ) {
    // Price calculation
    $new_price = $cart_data['data']->get_price() * 2;

    // Set and register the new calculated price
    $cart_data['data']->set_price( $new_price );
    $cart_data['new_price'] = $new_price;

    return $cart_data;
}

add_filter( 'woocommerce_get_cart_item_from_session', 'set_custom_cart_item_prices_from_session', 20, 3 );
function set_custom_cart_item_prices_from_session( $session_data, $values, $key ) {
    if ( ! isset( $session_data['new_price'] ) || empty ( $session_data['new_price'] ) )
        return $session_data;

    // Get the new calculated price and update cart session item price
    $session_data['data']->set_price( $session_data['new_price'] );

    return $session_data;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and working. It will change all prices as you expect in cart, checkout and order pages…




回答2:


Is there a way too pass a variable across in to the function and return venerable price instead?

add_filter( 'woocommerce_product_get_price', 'run_shortcodes_on_prices', 10, 3 );

function run_shortcodes_on_prices( $price , $string, $product){
    if( is_shop() || is_product_category() || is_product_tag() || is_product() )

    return $string;
}


来源:https://stackoverflow.com/questions/47788254/checkout-price-issue-using-woocommerce-product-get-price-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!