how to add shipping cost woocommerce code example

Example 1: get current shipping method woocommerce

$rate_table = array();

$shipping_methods = WC()->shipping->get_shipping_methods();

foreach($shipping_methods as $shipping_method){
    $shipping_method->init();

    foreach($shipping_method->rates as $key=>$val)
        $rate_table[$key] = $val->label;
}

echo $rate_table[WC()->session->get( 'chosen_shipping_methods' )[0]];

Example 2: woocommerce display shipping cost on product page

add_action('woocommerce_single_product_summary', 'display_specific_shipping_class', 15 );
function display_specific_shipping_class(){
    global $product;

    // HERE define your targeted shipping class name
    $defined_shipping_class = "Estimated Delivery in 7-15 days";

    $product_shipping_class = $product->get_shipping_class();

    // Get the product shipping class term name
    $term_name = get_term_by( 'slug', $product_shipping_class, 'product_shipping_class' );

    if( $term_name == $defined_shipping_class ){
        echo '<p class="product-shipping-class">' . $term_name . '</p>';
    }
}

Example 3: Woocommerce custom Flat Rate charges (by ID) Function

function wc_ninja_change_flat_rates_cost( $rates, $package ) {

  // Make sure flat rate is available
  // '13' is Flat Rate ID (What you Define)
	if ( isset( $rates['flat_rate:13'] ) ) {
		// Set the cost to $100
		$rates['flat_rate:13']->cost = 60;
		
	}
		return $rates;
}

add_filter( 'woocommerce_package_rates', 'wc_ninja_change_flat_rates_cost', 10, 2 );

Tags:

Php Example