John Davidson

php - Magento2 hide custom shipping method based on product attribute

0 comments
Message:


I am new to Magento2.


I have created a new shipment method programmatically and name it "Same Day Delivery".
Also, I have created a product attribute programmatically and name it "Same Day Delivery Available: (Yes/No).


I would like to add the restriction on the Checkout page - If all items in cart have (Same Day Delivery Available as Yes). Then display the new shipment option or hide them in the shipment selection section.


Here is my source code:
https://github.com/balajimrv/app



My Answer:
"Custom Shipping Method." Now, I want to hide this custom shipping method based on a specific product attribute. How can I achieve this in Magento2?

To hide the custom shipping method based on a specific product attribute in Magento2, you can create a plugin for the `Magento\Quote\Model\ShippingMethodManagement` class. Here's a step-by-step guide on how to achieve this:

1. Create a new module in Magento2 and define a `di.xml` file in the `etc` directory of your module.

2. In the `di.xml` file, define a plugin for the `Magento\Quote\Model\ShippingMethodManagement` class:

xml







3. Create a new PHP file `ShippingMethodManagementPlugin.php` in the `Plugin` directory of your module and implement the logic to hide the custom shipping method based on the product attribute:

php

namespace Vendor\Module\Plugin;

use Magento\Quote\Model\ShippingMethodManagement;

class ShippingMethodManagementPlugin
{
public function afterGetShippingMethods(
ShippingMethodManagement $subject,
$result
) {
$filteredMethods = [];

foreach ($result as $method) {
// Check if the custom shipping method should be hidden based on product attribute
if ($this->shouldHideCustomShippingMethod($method)) {
continue;
}

$filteredMethods[] = $method;
}

return $filteredMethods;
}

private function shouldHideCustomShippingMethod($method)
{
// Implement your logic here to check if the custom shipping method should be hidden based on product attribute
// You can use the $method object to access product information

return false; // Return true if the custom shipping method should be hidden
}
}


4. Implement the `shouldHideCustomShippingMethod` method in the `ShippingMethodManagementPlugin` class to check if the custom shipping method should be hidden based on the product attribute. You can access the product information from the `$method` object passed to the method.

5. Update the logic in the `shouldHideCustomShippingMethod` method to return `true` if the custom shipping method should be hidden based on the product attribute.

By following these steps, you can create a plugin in Magento2 to hide the custom shipping method based on a specific product attribute.

Rate this post

5 of 5 based on 3677 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us