WooCommerce – How to Add a Custom Field to Cart Items and Cart Totals [closed]

First, store the custom field when you’re editing your product. Lets say you’re using the custom_shipping_cost custom field. Make sure its stored as a number, 20 for example, NOT $20.00

Then, you need to display this field on the cart page. Sadly, theres no filter for adding a new column in the cart table, so you need to edit the template file, or if its not required to be a column, you can do this instead, this code will add the extra value to the last column:

add_filter('woocommerce_cart_item_subtotal','additional_shipping_cost',10,3);
function additional_shipping_cost($subtotal, $values, $cart_item_key) {
    //Get the custom field value
    $custom_shipping_cost = get_post_meta($post->ID, 'custom_shipping_cost', true);

    //Just for testing, you can remove this line
    $custom_shipping_cost = 10;

    //Check if we have a custom shipping cost, if so, display it below the item price
    if ($custom_shipping_cost) {
        return $subtotal.'<br>+'.woocommerce_price($custom_shipping_cost).' Shipping Cost';
    } else {
        return $subtotal;   
    }
}

So with this, the first part of the question is done. If you want to display it as your example above, you need to duplicate the plugins/woocommerce/templates/cart/cart.php file to themes/yourtheme/woocommerce/cart/cart.php. Then edit the file, add your own column, you can use the code above to display the price.

After this, we need to update the cart totals with the additional costs. Your code with the add_fee comes in handy:

function woo_add_cart_fee() {
    global $woocommerce;

    $extra_shipping_cost = 0;
    //Loop through the cart to find out the extra costs
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
        //Get the product info
        $_product = $values['data'];

        //Get the custom field value
        $custom_shipping_cost = get_post_meta($_product->id, 'custom_shipping_cost', true);

        //Just for testing, you can remove this line
        $custom_shipping_cost = 10;

        //Adding together the extra costs
        $extra_shipping_cost = $extra_shipping_cost + $custom_shipping_cost;
    }

    //Lets check if we actually have a fee, then add it
    if ($extra_shipping_cost) {
        $woocommerce->cart->add_fee( __('Shipping Cost', 'woocommerce'), $extra_shipping_cost );
    }
}
add_action( 'woocommerce_before_calculate_totals', 'woo_add_cart_fee');

Thats it, it should work after this. Make sure to remove the Just for testing… lines from both of the codes, i didn’t created the custom field on my site for testing.

Leave a Comment