What can we help you with?

10 Handy Customizations for USPS and Stamps.com Shipping Plugins for WooCommerce (Code Snippets)

Plugins are developed keeping in view of the basic need related to the field. For example, many shipping plugins show shipping rates, print label and provide tracking services. A payment gateway covers most service providers and will have a security add-on with it. But in certain cases, shop owners may require to customize their plugins.

In WooCommerce, to get customization to work, you have to copy and paste code snippets into your theme functions.php file. First, find it by going to  Appearance –> Editor –> functions.php. Next, paste the code snippet there. Once you save changes, these will be available in your WooCommerce settings.

In this article, we’ll see 10 Handy customizations for USPS and Stamps.com Shipping Plugins for WooCommerce.

1. Assign a Default Weight for the Products

Consider a situation where you add new products to your store and forget to assign weights to them. Under normal circumstances, USPS will not return rates if there is no weight assigned to the product.

To avoid this situation, can add this code snippet, and automatically assign a default weight for the products those have no weight. Below code snippet assigns a default weight for the products those have no weight assigned already. You can assign any numerical value to  $default_weight = 1. Here it is 1 pound.

add_filter('woocommerce_product_get_weight', 'add_weight', 10, 2);
function add_weight($weight, $product){
    $default_weight = 1; //give here the default weight, which will consider if there is no any wight assigned to the products.
    if( empty($weight) ){
        return $default_weight;
    }
    else{
        return $weight;
    }
}

2. Hide Shipping Methods based on Order Weight

Order weight refers to the weight of items in the cart. This code snippet will allow you to hide shipping methods based on the weight of the package. If the weight is less than a certain value, you can hide the shipping methods which are mentioned in the code snippet.

Let’s suppose you have selected all the USPS services on the Settings page. And you want to hide some specific shipping method based on weight such as letters or media mails, use the code snippet below. In the given code we have item weight as 160 oz “($weight_oz >= 160)”. You can change the value by replacing 160.

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

function show_shipping_method_on_order_weight( $available_shipping_methods, $package ) {
	
	$order_weight = 0;
	foreach( WC()->cart->cart_contents as $key => $values ) { 
		$product_weight	= woocommerce_get_weight($values[ 'data' ]->get_weight(),'lbs');
		$quantity 		= $values['quantity'];
		if($product_weight && $quantity){
			$order_weight = $order_weight + $product_weight*$quantity;
		}
	}
	$weight_oz = $order_weight*16;
//echo"weight_oz $weight_oz";die;
	if($weight_oz >= 160){
		$shipping_services_to_hide	=	array(
			'wf_usps_stamps',
			'wf_usps_stamps:US-XM',
			'wf_usps_stamps:US-EMI',
			'wf_usps_stamps:US-PM',
			'wf_shipping_usps:D_STANDARD_POST',
			'wf_shipping_usps:D_MEDIA_MAIL',
			'wf_shipping_usps:D_LIBRARY_MAIL',
			'wf_shipping_usps:D_PRIORITY_MAIL',
			'wf_shipping_usps:I_EXPRESS_MAIL',
			'wf_shipping_usps:I_PRIORITY_MAIL',
			'wf_usps_stamps',
			'wf_shipping_usps:I_FIRST_CLASS',
			'wf_shipping_usps:I_POSTCARDS',	
			
		
		);
	}else{
		$shipping_services_to_hide	=	array('flat_rate');
	}
	
	foreach ( $shipping_services_to_hide as $key => $value ) {
	//echo"value <pre>";print_r($value);echo"</pre>";
		unset( $available_shipping_methods[$value] );
		//unset($value);	
	}

	return $available_shipping_methods;
}

You can add or remove any service by editing the right shipping method Id in the code. Add more services in the format ‘wf_shipping_usps:I_PRIORITY_MAIL’, along with the other services.

3. Hide Shipping Method Based on Item Count

Item Count is the total number of items in the cart. This snippet will help you set a minimum number of items per order to show free shipping options. In other words, when you wish to offer free shipping to customers who have 5 or more items in the cart. Set the minimum number of items required on the cart in this line of the code: $minimum_number_of_item = 5;

In the present code snippet, it is 5. If the number of items is less than 5, free shipping option will not be available. Regular shipping methods will be shown to the customers having less than 5 items.

add_filter('woocommerce_package_rates', 'show_hide_free_shipping', 10, 2);
function show_hide_free_shipping($available_shipping_methods, $package){
    $minimum_number_of_item = 5; //Give here minimum number of items to allow freeshipping

    $free_shipping  =  false;
    global $woocommerce;
    $customer_country = $woocommerce->customer->get_shipping_country();

    $item_count = 0;
    foreach (WC()->cart->cart_contents as $key => $item) {
        $item_count += $item['quantity'];
    }

    if( $item_count >= $minimum_number_of_item ){
        $free_shipping  =  true;
    }

    if($free_shipping){
        unset($available_shipping_methods['wf_shipping_usps:D_FIRST_CLASS']);    
    }
    return $available_shipping_methods;
}

4. Hide Shipping Method Based on Order Cost

Order cost is the total cost of all the items in the cart. So if any customer crosses a certain $ mark, you can hide Flat rate shipping method when the total in the cart has a minimum total. For example, you want to offer free shipping when the cart total is $100. So set the order total limit to $100 in the line $order_total_limit = 100;

Then configure the flat rate ID that is to be hidden in the next line. Ensure that you write the free shipping ID as mentioned in the settings. Then give the name of the shipping method you want to show.

To summarize, with this snippet you hide one shipping option when the cart total crosses a certain limit. At the same time, you show Free Shipping to the customer.

add_filter('woocommerce_package_rates', 'wf_remove_shipping_options_basedon_cart_total', 10, 2);    
    function wf_remove_shipping_options_basedon_cart_total($rates, $package){
        global $woocommerce;
        $order_total_limit  = 50; //Set here limit of cart total
        $method_to_hide_when_cross_limit = array(
            'flat_rate:03'  // configure the flat rate ID that needs to be hidden
        );
        
        $method_to_show_when_cross_limit = array(
            'free_shipping:1' //config here exact freeshipping ID of you cart
        );

        $cart_total = WC()->cart->cart_contents_total;
        if ( $cart_total >= $order_total_limit ) {
            foreach ($method_to_hide_when_cross_limit as $shipping_method) {
                unset( $rates[$shipping_method] );
            }
        }else{
            foreach ($method_to_show_when_cross_limit as $shipping_method) {
                unset( $rates[$shipping_method] );
            }
        }
        return $rates;
    }

5. Hide Shipping Methods when Free Shipping or Flat Rate Exists

Many times you want to show only free shipping or flat rate for local customers. And that should happen once any address is entered with the ZIP code or as soon as any other criteria are fulfilled by the items in the cart. Also, other shipping options should not be shown to customers in such cases.

So, this customization code snippet hides any other shipping services when there is a valid free shipping of flat rate setting is available.

add_filter('woocommerce_package_rates', 'xa_hide_shipping_methods_if_free_flaterate_exist', 10, 2);
if(!function_exists('xa_hide_shipping_methods_if_free_flaterate_exist')){
    function xa_hide_shipping_methods_if_free_flaterate_exist( $available_shipping_methods, $package ){

        $hide_if_shpping_method_exist = array('free_shipping','flat_rate'); //If the shipping methods given here is exists.
        $method_to_hide = array('wf_dhl_shipping'); //Hide all the shipping method provided here.

        $do_hide = false;
        foreach ($hide_if_shpping_method_exist as $method) {
            foreach ($available_shipping_methods as $shipping_method => $value) {
                if( strpos( $shipping_method, $method ) !== false ) {
                    $do_hide=true;
                    break 2;
                }
            }
        }

        if( $do_hide ){
            foreach ($method_to_hide as $method) {
                xa_hide_the_shipping_method( $method, $available_shipping_methods );
            }
        }
        return $available_shipping_methods;
    }
}

if(!function_exists('xa_hide_the_shipping_method')){
    function xa_hide_the_shipping_method($method, &$available_shipping_methods){
        foreach ($available_shipping_methods as $shipping_method => $value) {
            if( strpos( $shipping_method, $method ) !== false ) {
                unset($available_shipping_methods[$shipping_method]);
            }
        }
        return $available_shipping_methods;
    }
}

6. Hide Shipping Method when Shipping Class Exists: Flat Rate

We sometimes put certain items in one class and define a Flat rate for that class. So for classes having Flat Rate, you can use the following code to hide rest of the shipping methods. This customization code snippet helps you to show only the Flat Rate on the cart page/checkout.

add_filter('woocommerce_package_rates', 'wf_hide_shipping_method_based_on_shipping_class', 10, 2);
	
function wf_hide_shipping_method_based_on_shipping_class($available_shipping_methods, $package)
{
    $hide_when_shipping_class_exist = array(
        74=> array(
            'flat_rate:8'
        )
    );
    
    $hide_when_shipping_class_not_exist = array(
    );
    
    
    $shipping_class_in_cart = array();
    foreach($package['contents'] as $key => $values) {
       $shipping_class_in_cart[] = $values['data']->get_shipping_class_id();
    }

    foreach($hide_when_shipping_class_exist as $class_id => $methods) {
        if(in_array($class_id, $shipping_class_in_cart)){
            foreach($methods as & $current_method) {
                unset($available_shipping_methods[$current_method]);
            }
        }
    }
    foreach($hide_when_shipping_class_not_exist as $class_id => $methods) {
        if(!in_array($class_id, $shipping_class_in_cart)){
            foreach($methods as & $current_method) {
                unset($available_shipping_methods[$current_method]);
            }
        }
    }
    return $available_shipping_methods;
}

7. Set Maximum Shipping Charges

This customization code snippet will help you assign a maximum shipping charge based on shipping destination. For example, you might want to charge a maximum of $25 to any domestic customer and a maximum of $50 to an international customer.

So if the actual USPS shipping charges for any item is $30, your domestic customer will still see $25. Similarly, your international customers will see only $50 as the shipping charge for any charge greater than $50. You can change the value in the codes as per your need by editing the numerical values. If you are not based in the USA, you need to set the Origin Country too.

add_filter('woocommerce_package_rates', 'wf_modify_rate', 10, 3);
function wf_modify_rate( $available_shipping_methods, $package ){
    $origin_country = 'CA';
    $max_amount_domestic = 25;
    $max_amount_international = 50;

    $max_amount = ($package['destination']['country'] == $origin_country) ? $max_amount_domestic : $max_amount_international;

    $item_count = 0;
    foreach ($package['contents'] as $key => $item) {
        $item_count += $item['quantity'];
    }

    foreach ($available_shipping_methods as $methord_name => $methord) {
        if( $max_amount < $available_shipping_methods[$methord_name]->cost ){
            $available_shipping_methods[$methord_name]->cost = $max_amount;
        }
    }
    return $available_shipping_methods;
}

8. Modifying Product Title and Price in Stamps.com Label

Stamps.com allows printing of Hidden postages. Apart from the built-in feature, you can use the following code to modify the product title and price in the printed label. In the snippet, ‘Mobile phone’ is changed into ‘Cellphone’ and the cost is modified to $500.

So the modification will be applied to every product in stamps label.

add_filter('wf_stamps_request', 'wf_customize_stamps_products_title', 10, 2);
function wf_customize_stamps_products_title( $request, $order ){
    $new_product_titles = array(
        //Config this array with product name with corresponding values
        'Mobile phone'=> array(
            'Description' =>'Cell Phone', //new description. Leave this blank if no need to change.
            'Value' => 500 //new price of the item. Leave this blank if no need to change.
        ),
    );
    if( isset($request['Customs']['CustomsLines']['CustomsLine']) ){
	    foreach ($request['Customs']['CustomsLines']['CustomsLine'] as $key => $customs_items) {
	        if( array_key_exists($customs_items['Description'], $new_product_titles ) ){
	            if( !empty( $new_product_titles[ $customs_items['Description'] ]['Value'] ) ){
	               $request['Customs']['CustomsLines']['CustomsLine'][$key]['Value'] = $new_product_titles[ $customs_items['Description'] ]['Value'];
	            }
	            if(!empty( $new_product_titles[ $customs_items['Description'] ]['Description'] )){
	               $request['Customs']['CustomsLines']['CustomsLine'][$key]['Description'] = $new_product_titles[ $customs_items['Description'] ]['Description'];
	            }
	        }
	    }
	}

    return $request;
}

9. Hide Shipping Method based on Shipping Class: Local Pickups

Local pickups mean that the shipped items will be retained at local stations of the carrier. This is similar to the 7th snippet. Here you can hide other shipping methods when the shipping destination falls under the local pickup zone.

For example, you offer only local pickup in a certain part of your state. So as soon as any customer enters the ZIP code of the locality of local pickups, other shipping methods are hidden.

//add_filter('woocommerce_package_rates', 'wf_hide_shipping_method_based_on_shipping_class', 10, 2);
	
function wf_hide_shipping_method_based_on_shipping_class($available_shipping_methods, $package)
{
    $hide_when_shipping_class_exist = array(
        18=> array(
            'local_pickup:3'
        )
    );
    
    $hide_when_shipping_class_not_exist = array(
    );
    
    
    $shipping_class_in_cart = array();
    foreach($package['contents'] as $key => $values) {
       $shipping_class_in_cart[] = $values['data']->get_shipping_class_id();
    }

    foreach($hide_when_shipping_class_exist as $class_id => $methods) {
        if(in_array($class_id, $shipping_class_in_cart)){
            foreach($methods as & $current_method) {
                unset($available_shipping_methods[$current_method]);
            }
        }
    }
    foreach($hide_when_shipping_class_not_exist as $class_id => $methods) {
        if(!in_array($class_id, $shipping_class_in_cart)){
            foreach($methods as & $current_method) {
                unset($available_shipping_methods[$current_method]);
            }
        }
    }
    return $available_shipping_methods;
}

10. Enhance the Checkout Process for PO Box Addresses

A PO Box or Post Office Box is a lockable box located in a post office which customers can rent out. In the United States, PO Boxes are generally available through the United States Postal Service (USPS). Other major shipping carriers such as UPS, FedEx, DHL etc. have alternate solutions to this, but none able to directly deliver to a PO Box.

 This code snippet will limit the services of other carriers and only show USPS rates in checkout when PO Box is entered in ‘address line 1’ instead of a street address.

add_filter('woocommerce_package_rates', 'wf_hide_fedex_for_po_box_shipment', 10, 2);    
function wf_hide_fedex_for_po_box_shipment($available_shipping_methods, $package){
    $shipping_method_to_hide = 'wf_fedex_woocommerce_shipping';
    global $woocommerce;
    $address  = ( !empty( $woocommerce->customer->get_shipping_address_1() ) ) ? $woocommerce->customer->get_shipping_address_1() : $woocommerce->customer->get_billing_address_1();
    $postcode = ( !empty( $woocommerce->customer->get_shipping_postcode() ) ) ? $woocommerce->customer->get_shipping_postcode() : $woocommerce->customer->get_billing_postcode();

    if ( strstr( $address, 'pobox' ) || strstr( $postcode, 'pobox' ) ) {
        foreach ($available_shipping_methods as $shipping_method => $value) {
            if( strpos( $shipping_method, $shipping_method_to_hide ) !== false ) {
                unset($available_shipping_methods[$shipping_method]);
            }
        }
    }
    return $available_shipping_methods;
}

Concluding Comments

These plugin customizations are Developer level documents. It may be possible that you are not familiar with the code and the potential conflicts in the logic involved. In such case contact our online support or leave a comment in the comments section below. If you are subscribed to any of our product, you receive fee customization and premium support for a year at the same cost of the product. Premium updates, support and customization can be renewed at 50% discount for a year. Contact our online support for any of your pre- and post sales queries. Visit our product page for new and exciting premium plugins for WooCommerce.

Previous How to display product dimension in Shipment labels in WooCommerce Stamps.com Plugin? (Code Snippet)
You must be logged in to post a comment.