1

I want to set custom shipping method programmatically if product have custom attribute in magento 2

.I am using checkout_cart_add_product_complete event and getting product attribute after adding in cart.

etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

    <event name="checkout_cart_add_product_complete">
        <observer name="checkout_cart_product_add_after_add_shipping"
                  instance="Sarvesh\Tiwari\Observer\CheckoutCartProductAddAfter"/>
    </event>
</config>

observer/CheckoutCartProductAddAfter.php

$item = $observer->getEvent()->getData('quote_item');
        $product = $observer->getEvent()->getData('product');
        $itemProId = $item->getProduct()->getId();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product_data = $objectManager->create('Magento\Catalog\Model\Product')->load($itemProId);
        $supplier = $product_data->getData('supplier');
        if(isset($supplier) && $supplier!=''){
            if($supplier=='supplier_a'){
                //echo 'Supplier a add Shipping Method UPS';
            $quote = $observer->getEvent()->getQuote();
            $quote->getShippingAddress()->setFlateRate(true);
            $quote->save();
            }elseif($supplier=='supplier_b'){
                //echo 'Supplier b add Shipping Method FedeX';
               $quote = $observer->getEvent()->getQuote();
                $quote->getShippingAddress()->setFlateRate(true);
                $quote->save();
            }elseif($supplier=='supplier_b' && $supplier=='supplier_a'){
                echo 'both A && B apply both shipping Method';
            }
        }

how to set custom shipping method in magento 2.

2
  • Hi, did you solve this? Apr 7, 2021 at 12:25
  • 1
    Yes, I fetch product attributes in shipping.html, and as per conditions marked shipping method. Apr 8, 2021 at 5:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.