Skip to content

disable a cash on delivery payment method on the checkout for specific products

I want to disable a cash on delivery payment method on the checkout for specific products
I followed the code in this question

Disable Payment Method at Checkout in Magento 2 Based on Product Attribute

I modified the payment name in this file

Vendor/DisableCOD/Observer/DisablePaymentMethods.php

to cashondelivery

<?php
namespace VendorDisableCODObserver;
use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkAppObjectManager;
class DisablePaymentMethods implements ObserverInterface
{
    public function __construct(PsrLogLoggerInterface $logger)
    {
        $this->_logger = $logger;
    }
    /**
     *
     * @param MagentoFrameworkEventObserver $observer
     * @return void
     */
    public function execute(MagentoFrameworkEventObserver $observer)
    {
        $objectManager = MagentoFrameworkAppObjectManager::getInstance();
        $cart = $objectManager->get('MagentoCheckoutModelCart'); 

        // get cart items
        $items = $cart->getItems();

        // get attribute value of cart items
        foreach ($items as $item) 
        {
            $p = $objectManager->get('MagentoCatalogModelProduct')->load($item['product_id']);
            $attribute = $p->getResource()->getAttribute('cod'); 

            if ($attribute) 
            {
                $attr_value = $attribute ->getFrontend()->getValue($p);
                if($attr_value == 'Yes' || $attr_value == 'yes' || $attr_value == 'YES')
                {
                    if($observer->getEvent()->getMethodInstance()->getCode()=="cashondelivery")
                    {
                        $checkResult = $observer->getEvent()->getResult();
                        $checkResult->setData('is_available', false); 
                    }
                }

            }
        }
    }
}

then I created new Product Attribute that named ‘cod’ with input type ‘Yes/No’
but nothing happened the cash on delivery method still enabled for