PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 23, 2022

[FIXED] How to make shipping cost free Magento 2 for a custom shipping method

 August 23, 2022     magento2, php     No comments   

Issue

I managed to create my custom shipping method as flatrate with a custom module the shipping costs 5$.

I want to make it free if the cart total is more than 30$ for example.

Is there anyway to do this ?

I have no clue from where to start so I have no code to try please help.

Thanks !


Solution

Found it, In case someone needs this :

In my shipping.php file there is a function called collectRates which is reponsible for returning the shipping rates, I added

    if($request->getBaseSubtotalInclTax()>100){
        $method->setPrice(0);
    }

Basically If the total is more than 100$ I make the shipping price free, It would be better to make the 100$ a dynamic value which can be changed in the shipping method settings I will do it later.

this is my collectRates Function in the end:

 * @param RateRequest $request

 * @return bool|Result

 */

public function collectRates(RateRequest $request)

{
    if (!$this->getConfigFlag('active')) {
        return false;
    }

    /** @var \Magento\Shipping\Model\Rate\Result $result */

    $result = $this->_rateResultFactory->create();

    /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */

    $method = $this->_rateMethodFactory->create();
    $method->setCarrier($this->_code);
    $method->setCarrierTitle($this->getConfigData('title'));
    $method->setMethod($this->_code);
    $method->setMethodTitle($this->getConfigData('name'));
    $amount = $this->getShippingPrice();
    $method->setPrice($amount);
    if($request->getBaseSubtotalInclTax()>100){
        $method->setPrice(0);
    }
    $method->setCost($amount);
    $result->append($method);
    return $result;

}


Answered By - Nicole
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing