WordPress Snippets at WPcustoms

Add shipping costs to WooCommerce

Add shipping costs to your WooCommerce shop. Save it via a custom meta field. If you got $10.00 simply enter 10
The custom meta field value needs to manually added to your shopping cart template. There is no hook to insert that with a function.


/**
 * Snippet Name: Add shipping costs to WooCommerce
 * Snippet URL: https://wpcustoms.net/snippets/add-shipping-costs-woocommerce/
 */
  function wpc_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);

    //Check if we have a custom shipping cost, if so, display it below the item price
    if ($custom_shipping_cost) {
        return $subtotal.'
+'.woocommerce_price($custom_shipping_cost).' Shipping Cost'; } else { return $subtotal; } } add_filter('woocommerce_cart_item_subtotal','wpc_additional_shipping_cost',10,3); function wpc_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 - make sure it's i.e. 10 not $10.00 $custom_shipping_cost = get_post_meta($_product->id, 'custom_shipping_cost', true); //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', 'wpc_add_cart_fee');