How to create a custom shipping method
Adding a custom shipping method in Magento 2 can be relatively easy depending on the functionality that is needed. In this tutorial, we will show you how to add a simple basic flat rate custom shipping method in Magento 2.
Create a new module
The first step would be to create a new module to handle the new custom shipping method.
Register the new module
We need to register the new module by creating a registration.php file.
You will need to replace Vendor/ModuleName with your vendor and module's name. For the sake of this article, we will replace it with MeTutorials/CustomShipping.
Next, let's add the following code to the registration.php file.
Create the module's composer.json file
Next, add the following code to our composer.json file located at: app/code/MeTutorials/CustomShipping/composer.json
Create the module's module.xml file
Next, add the following to the module's module.xml file located here: app/code/Vendor/CustomShipping/etc/module.xml
Create the module's configuration file
This will allow the admin to control the settings of the custom shipping method from the Magento 2 backend. Let's create the following file and add the following code.
Specify default values and declare our Carrier Model
Next, we can specify some default values and tell Magento which carrier model (MeTutorials\CustomShipping\Model\Carrier\CustomShipping) to use for our new custom shipping method. Simply create the following file and add the following code.
Create our new Carrier Model
Next, let's create our new carrier model located at app/code/MeTutorials/CustomShipping/Model/Carrier/Customshipping.php and insert the following code.
As you can see here, our new carrier model inherits the CarrierInterface interface which allows the getAllowedMethods() method to use all of the available shipping methods. The collectRates() method returns the \Magento\Shipping\Model\Rate\Result object on checkout if it is available. If it is not available, it will return false.
Enable our new module
Configure the settings
Finally, navigate to Stores > Configuration > Sales > Shipping Methods. You should see your new Custom Shipping method and will be able to configure it here as well.
As you can see from the above example, adding a new custom shipping method to Magento 2 can be fairly straightforward. The above example can also be extended upon even further for more functionality depending on your needs.
If this article has helped you, please let us know below. We love to hear from all our readers! Feel free to download our free Magento 2 Custom Shipping Method extension. To learn more about custom shipping methods feel free to take a look at Magento's documentation as well which can be seen here.