Checkout price issue using woocommerce_product_get

2019-07-04 16:09发布

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.

2条回答
\"骚年 ilove
2楼-- · 2019-07-04 16:30

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;
}
查看更多
太酷不给撩
3楼-- · 2019-07-04 16:32

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…

查看更多
登录 后发表回答