Checkout price issue using woocommerce_product_get_price hook

后端 未结 1 734
感情败类
感情败类 2021-01-06 13:28

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\', \'do         


        
相关标签:
1条回答
  • 2021-01-06 13:42

    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…

    0 讨论(0)
提交回复
热议问题