Remove the product assignment from the category by category id and SKU in Magento 2 useful for removing unnecessary products from the Category by Programmatic approach.
Let’s We want to delete the product has SKU “24-MB04” from the Watches Category in Native Magento with Sample data.
We required category id for Watches Category is 6 and We have already product SKU, Use interface class, Magento\Catalog\Api\CategoryLinkRepositoryInterface and method deleteByIds() to remove / unassigned products from the Category.
<?php
namespace Jesadiya\UnassignedProduct\Model;
use Exception;
use Magento\Catalog\Api\CategoryLinkRepositoryInterface;
class UnassignedProductFromCategory
{
/**
* @var CategoryLinkRepositoryInterface
*/
private $categoryLinkRepository;
public function __construct(
CategoryLinkRepositoryInterface $categoryLinkRepository
) {
$this->categoryLinkRepository = $categoryLinkRepository;
}
/**
* Assigned Product to single/multiple Category
*
* @param int $categoryId
* @param string $sku
* @return bool
*/
public function unassignedProductFromCategory($categoryId, $sku)
{
$isProductUnassigned = false;
try {
$isProductUnassigned = $this->categoryLinkRepository->deleteByIds($categoryId, $sku);
} catch (Exception $exception) {
throw new Exception($exception->getMessage());
}
return $isProductUnassigned;
}
}
Pass required parameter from the method definition,
$sku = "24-MB04"; $categoryId = "6"; $productAssigned = $this->unassignedProductFromCategory($sku, $categoryId);
Output:
Boolean
Run Indexer command:
php bin/magneto indexer:reindex catalog_category_product catalog_product_category
When you check the Gear -> Watches Category from the front end, Product Aim Analog watch not display to the Category.
