I have created custom shipping method named ad My Shipping Method and have created custom attribute named my_Shipping_charge. Both are working fine without any error. Now I want to set condition if my_Shipping_charge has any value then it will consider it as shipping charge otherwise default charges of My Shipping Method should be apply.

For example,
default charges set in My Shipping Method is 10
my_Shipping_charge for product A is null
my_Shipping_charge for product B is 15
my_Shipping_charge for product C is 5

Then total shipping charge should be 10+15+5

    private function getShippingPrice()
        $configPrice = $this->getConfigData('price');
        $shippingPrice = $this->getFinalPriceWithHandlingFee($configPrice);

        /*To find cart details */
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $cart = $objectManager->get('\Magento\Checkout\Model\Cart');        

        /*To find number of items available in cart */ 
        $itemsVisible = $cart->getQuote()->getAllVisibleItems();
        $itemNum = count($itemsVisible);

        /*To find quantity of item */
        $items = $cart->getQuote()->getAllItems();

        $finalShippingChargeOfProduct = 0;

        foreach($items as $item) {

            $qty = $item->getQty();
            $product_id = $item->getProductId();
            $customProduct = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id); 
            $myShippingAtt = $customProduct->getData('my_shipping_charge');
            settype($myShippingAtt, "integer");

            if($myShippingAtt <= 0)
                $finalShippingChargeOfProduct += $shippingPrice*$qty;
                $finalShippingChargeOfProduct += $customProduct->getData('my_shipping_charge')*$qty;
        return $finalShippingChargeOfProduct; 

Everything is working fine but error in loop. custom attribute value is not correct everytime.

  • is this working for admin new orders? – Sourav Apr 18 at 17:15


$customProduct = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);


$customProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);

Suggestion: use product repository instead of using object manager and deprecated load method

  • Thanks a lot..!!! @sohel It's working perfectly. – Khooshbu Patel Feb 27 at 10:14

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.