I plugin the Magento\Shipping\Model\Shipping::collectRates() method after getting the hint from the solution provided by @Ronak Rathod. Here is the solution that is working fine for me.
In Module 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\Shipping\Model\Shipping">
<plugin name="in_store_pickup_shipping_method_hide" type="Vendor\InStorePickup\Plugin\AfterShippingCollectRates"/>
</type>
</config>
And Code for my plugin is as follow.
<?php
namespace Vendor\InStorePickup\Plugin;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Quote\Model\Quote\Address\RateRequest as RateRequest;
use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory;
use Magento\Quote\Model\Quote\Address\RateResult\Method;
use Magento\Shipping\Model\Rate\Result;
use Magento\Shipping\Model\Shipping;
use Psr\Log\LoggerInterface;
class AfterShippingCollectRates
{
/**
* @var LoggerInterface
*/
protected LoggerInterface $_logger;
/**
* @var ErrorFactory
*/
private $rateErrorFactory;
/**
* @var RateRequest|null
*/
private $request = null;
public function __construct(
ErrorFactory $rateErrorFactory,
LoggerInterface $logger
) {
$this->rateErrorFactory = $rateErrorFactory;
$this->_logger = $logger;
}
/**
* @param Shipping $subject
* @param RateRequest $request
* @return void
*/
public function beforeCollectRates(
Shipping $subject,
RateRequest $request
) {
$this->request = $request;
}
/**
* @param Shipping $subject
* @param $result
* @return Shipping
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function afterCollectRates(Shipping $subject, $result)
{
$result = $subject->getResult();
$rates = $result->getAllRates();
$result->reset();
foreach ($rates as $rate) {
$restrict = false;
if ($rate->getCarrier() == 'instore') {
$checkIfStorePickupNeedtoBeHidden = $this->checkIfStorePickupNeedtoBeHidden();
if ($checkIfStorePickupNeedtoBeHidden) {
$restrict = true;
$this->setError($result, $rate);
}
}
if (!$restrict) {
$result->append($rate);
}
}
return $subject;
}
/**
* set error message
* @param Result $result
* @param Method $rate
*
* @return bool
*/
private function setError($result, $rate)
{
$errorMessage = __('Sorry, Pick in Store method is restricted for this Orders.');
if ($rate !== null && $errorMessage) {
$error = $this->rateErrorFactory->create();
$error->setCarrier($rate->getCarrier());
$error->setCarrierTitle($rate->getCarrierTitle().' ('.$rate->getMethodTitle().')');
$error->setErrorMessage($errorMessage);
$result->append($error);
}
}
}
Write down a custom function
checkIfStorePickupNeedtoBeHidden
in the same file (or Helper) and put the logic for hiding shipping method in it.
Reference: https://webkul.com/blog/restrict-custom-shipping-methods-magento2/