woocommerce how to make shipping cost based on cart total code example

Example 1: 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 2: add shipping rate based on cart total woocommerce

add_filter( 'woocommerce_package_rates', 'tl_shipping_on_price', 10, 2 );
function tl_shipping_on_price( $rates, $package ) {
 
    $total = WC()->cart->cart_contents_total;
	//echo $total;
    if( $total <= 500 ) {
 
        unset( $rates['flat_rate'] );
        unset( $rates['free_shipping'] );
 
    } elseif ( $total > 500 && $total < 1000 ) {
 
        unset( $rates['local_delivery'] );
        unset( $rates['free_shipping'] );
 
    } else {
		unset( $rates['local_delivery'] );
        unset( $rates['flat_rate'] );
	}
 
    return $rates;
}

Tags:

Php Example