Magento – calculate shipping cost in magento 2

magento2shipping

I want to set my shipping cost depending on the product weight.
if weight<=5kg, shipping cost=5AED
if weight>5kg, then shipping cost will be increased by 2AED for each 1kg.

Best Answer

You can find here a nice tutorial provided by Domagoj Potkoc from Inchoo.
It shows you the basics of how to create a shipping method in Magento 2.
It includes classes and configuration files.
But the example generates a flat rate shipping method.
You will need to modify the method \Inchoo\Shipping\Model\Carrier\Example::collectRates().
Instead of the line $amount = $this->getConfigData('price'); you should add this:

$weight = $request->getPackageWeight();
//default cost
$amount = 5;
//if the total weight is over 5 add 2 for each kg
if ($weight > 5) {
    $intWeight = ceil($weight)
    $amount += 2 * ($intWeight - 5);
} 

The rest of the code should be as in the tutorial. Of course feel free to change the namespaces and class names.

Related Topic