How to Add a Custom Shipping Method for WooCommerce

In this tutorial, I’ll walk you through the process of adding a new shipping method to WooCommerce using custom code. By the end of this tutorial, you will have a working shipping method that can be configured directly from the WooCommerce settings.

Create a Custom Shipping Class

WooCommerce relies on classes to define shipping methods. Let’s create a new class for our custom shipping method.

 

// Add a custom shipping method
function add_custom_shipping_method( $methods ) {
    $methods['custom_shipping'] = 'WC_Custom_Shipping_Method';
    return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'add_custom_shipping_method' );

// Define the custom shipping method class
class WC_Custom_Shipping_Method extends WC_Shipping_Method {

    public function __construct() {
        $this->id = 'custom_shipping';
        $this->method_title = __( 'Custom Shipping', 'woocommerce' );
        $this->method_description = __( 'A custom shipping method example.', 'woocommerce' );

        $this->enabled = "yes";
        $this->title = "Custom Shipping";

        $this->init();
    }

    public function init() {
        // Load settings
        $this->init_form_fields();
        $this->init_settings();

        // Save settings
        add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
    }

    public function calculate_shipping( $package = array() ) {
        $rate = array(
            'id' => $this->id,
            'label' => $this->title,
            'cost' => '10.00', // Flat rate shipping cost
            'calc_tax' => 'per_order',
        );
        $this->add_rate( $rate );
    }
}

 

Lastly, go to WooCommerce > Settings > Shipping and configure the new shipping method as you need.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!