How to Add a Custom Shipping Method for WooCommerce

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.

[cc lang="php" tab_size="2" lines="40"]
// 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 );
    }
} [/cc]

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

haris raza

Hi, I'm Haris Raza! With years of experience as a WordPress backend developer, I specialize in custom PHP development, WooCommerce plugin creation, and building custom themes from scratch. Whether it's developing WordPress plugins or customizing existing ones, my goal is to provide seamless and efficient solutions that meet your unique needs. When I'm not coding, you can find me keeping up with the latest tech trends and collaborating with fellow developers. Thanks for visiting, and happy coding http://www.wpharis.com