1

I'd like to create a module to enable the Table Rate Shipping Method if a product with a specific SKU is the customer cart.

How could I do that?

2

You can achieve this using below code.

di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Quote\Api\ShipmentEstimationInterface">
        <plugin name="table_rate_check" type="Vendor\Module\Plugin\ShippingPlugin" />
    </type>
</config>

ShippingPlugin.php

<?php
namespace Vendor\Module\Plugin;


class ShippingPlugin
{
    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $checkoutSession;

    /**
     * @param \Magento\Checkout\Model\Session $checkoutSession
     */   
    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession
    ) {
        $this->checkoutSession = $checkoutSession;
    }

    /**
     * Hide FlatRate shipping method
     *
     * @param \Magento\Quote\Api\ShipmentEstimationInterface $subject
     * @param \Magento\Quote\Api\Data\ShippingMethodInterface[] $methods
     * @return \Magento\Quote\Api\Data\ShippingMethodInterface[] $methods
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterEstimateByExtendedAddress(\Magento\Quote\Api\ShipmentEstimationInterface $subject, $methods) 
    {
        foreach($methods as $key => &$method) {

            if($method->getMethodCode() == 'tablerate') {
                if($this->checkTableRateShipping()) {
                   unset($methods[$key]);
                   break;
                }
            }
        }
        return $methods;

    }

    private function checkTableRateShipping()
    {
        $items = $this->checkoutSession->getQuote()->getAllVisibleItems();
        $showTableRate = false;
        foreach($items as $item)
        {
          if($item->getSku() == "SKU which needs to be allow") {
             $showTableRate = true;
             break;
          }
        }
        return ($showTableRate) ? false : true; 

    }


}

Make sure you have enabled table rate shipping method from admin. Let me know if any more help needed. Happy Coding :)

  • 1
    Hi @Rafael, Was it helpful for you? – Ramkishan Suthar Nov 19 '18 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.