0

I'm trying to restrict a shipping method in afterCollectRates based on a custom product attribute (which I'm injecting with the help of catalog_attributes.xml

public function afterCollectRates(Tablerate $tablerate, $result)
{
    $items = $this->checkoutSession->getQuote()->getAllVisibleItems();
    foreach ($items as $item) {
        if ($item->getProduct()->getMyAttribute()) {
            return false;
        }
    }
    return $result;
}

This hides the shipping method if there's a product with the attribute in cart. However, I need the exact opposite. I need to hide the shipping method if no product in cart does have the attribute.

Obviously the cart can have products with and without the attribute, so I can not simply do !$item->getProduct()->getBulkgood() since the function only accepts return: false;

Any way to make this work?

1 Answer 1

0

Try below code. It will only show the shipping method when item contains your attribute otherwise it will return false.

public function afterCollectRates(Tablerate $tablerate, $result)
{
    $items = $this->checkoutSession->getQuote()->getAllVisibleItems();
    foreach ($items as $item) {
        if ($item->getProduct()->getMyAttribute()) {
            return $result;
        }
    }
    return false;
}
1
  • Thanks, I will give it a try. I also found I can hook into aroundCollectCarrierRates method. There I could combine several shipping restrictions. I think this is even better, or do you think the after plugin is the better way to go? Thanks
    – zlep
    May 17, 2021 at 13:13

Your Answer

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

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