Magento 2: How To Remove Product from the categories Programmatically?

Remove PRODUCTS TO CATEGORIES programmatically

We have seen how to add products to categories in a previous blog.https://sbdevblog.com/magento-2-how-to-assign-product-to-categories-programmatically/.

Very often, we get the requirement to add or remove products programmatically. For example, we must create a console script or cron job to drag products from categories.

As we need to add products to categories, we also need to remove those products from categories.

In this blog, we will see how to remove products from categories in Magento 2.

I recommend to re-index after assigning/removing products from categories.

How To Remove Products from Categories Programmatically?

Let’s assume that we have created the essential files of the module. I am creating a service class responsible for assigning products to different categories.

Could you create a service class VendorName/ModuleName/Service class? Inside the app. In my case, VendorName is SbDevBlog, and ModuleName is Catalog.

Create RemoveProductsFromCategories.Php Inside SbDevBlog/Catalog/Services
<?php
/**
 * @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
 */
namespace SbDevBlog\Catalog\Services;

use Magento\Catalog\Model\CategoryLinkRepository;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\StateException;
use Psr\Log\LoggerInterface;

class RemoveProductsFromCategories
{
    /**
     * @var CategoryLinkRepository
     */
    private CategoryLinkRepository $categoryLinkRepository;

    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * Constructor For Service
     *
     * @param CategoryLinkRepository $categoryLinkRepository,
     * @param LoggerInterface $logger
     */
    public function __construct(
        CategoryLinkRepository $categoryLinkRepository,
        LoggerInterface $logger
    ){
        $this->categoryLinkRepository = $categoryLinkRepository;
        $this->logger = $logger;
    }

    /**
     * Remove Product From Category
     *
     * @param int $categoryId
     * @param string $sku
     *
     * @return bool
     */
    public function removeProductsFromCategory(int $categoryId, string $sku):bool
    {
        try { 
                $this->categoryLinkRepository->deleteByIds($categoryId, $sku);
                return true;
            } catch (CouldNotSaveException|InputException|StateException $e) {
                $this->logger->error($e->getMessage());
            }
        }
        return false;
    }
}

That’s it; removing a product from a category using the CategoryLinkRepository class is simple and easy. I hope it helps you.

Thanks for reading How To Remove Products from Categories Programmatically?

I hope Sb Dev Blog helps you. Feel free to ask questions or comment on posts. I welcome suggestions. I would like your suggestions to improve my knowledge and blogs.

Download Source Code

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *