phpwordpresswoocommercecart

Replace the price of the cart item with a custom field value in Woocommerce


In WooCommerce I am trying to replace the price of the cart items inwith a custom field price.

This is my code:

function custom_cart_items_price ( $cart_object ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    foreach ( $cart_object->get_cart() as $cart_item ) {

        // get the product id (or the variation id)
        $id = $cart_item['data']->get_id();

        // GET THE NEW PRICE (code to be replace by yours)
        $new_price = (int)get_post_meta( get_the_ID(), '_c_price_field', true ); // <== Add your code HERE

        // Updated cart item price
        $cart_item['data']->set_price( $new_price ); 
    }
}

add_filter( 'woocommerce_before_calculate_totals', 'custom_cart_items_price');

But it doesn't work. What I am doing wrong?

Any help will be appreciated.


Solution

  • It doesn't work if you use get_the_ID() with get_post_meta() in cart. You should use instead:

    add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_price');
    function custom_cart_items_price ( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
             return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        foreach ( $cart->get_cart() as $cart_item ) {
    
             // get the product id (or the variation id)
             $product_id = $cart_item['data']->get_id();
    
             // GET THE NEW PRICE (code to be replace by yours)
             $new_price = get_post_meta( $product_id, '_c_price_field', true ); 
    
             // Updated cart item price
             $cart_item['data']->set_price( floatval( $new_price ) ); 
        }
    }
    

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

    Now it should work