Hello Magento Lovers, Let's learn how we can stop product from getting add to cart programmatically. We need to use plugin interceptor method in order to restrict product from getting add to cart.

Create di.xml in app/code/Magefever/RestrictAddToCart/etc/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\Checkout\Model\Cart">
    <plugin name="interceptAddingProductToCart"
            type="Magefever\RestrictAddToCart\Model\Checkout\Cart\RestrictAddToCartPlugin"
            sortOrder="10"
            disabled="false"/>
  </type>
</config>
	

Create RestrictAddToCartPlugin.php in app/code/Magefever/RestrictAddToCart/Model/Checkout/Cart/RestrictAddToCartPlugin.php

    <?php
namespace Magefever\RestrictAddToCart\Model\Checkout\Cart;

use Magento\Framework\Exception\LocalizedException;

class RestrictAddToCartPlugin
{
    /**
     * @var \Magento\Quote\Model\Quote
     */
    protected $quote;

    /**
     * Plugin constructor.
     *
     * @param \Magento\Checkout\Model\Session $checkoutSession
     */
    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession
    ) {
        $this->quote = $checkoutSession->getQuote();
    }

    /**
     * beforeAddProduct
     *
     * @param      $subject
     * @param      $productInfo
     * @param null $requestInfo
     *
     * @return array
     * @throws LocalizedException
     */
    public function beforeAddProduct($subject, $productInfo, $requestInfo = null)
    {
        if ($this->quote->hasData('custom_attribute')) {
            throw new LocalizedException(__('Could not add Product to Cart'));
        }

        return [$productInfo, $requestInfo];
    }
}
	

Just Replace Magefever with your vendor name and RestrictAddToCart with your module name, run php bin/magento setup:di:compile once.