How to Disable/Enable a Product for Admin Store Programmatically in Magento 2

magento2multistoreproductsprogrammatically

I want to disable product for admin store means product should be disable for all store/website.
I am trying to do something like this but product disable for default store only:

$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
$productObj = $productRepository->get('sku');
$productObj->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
$productRepository->save($productObj);

I have also tried to pass global store id i.e. 0 like this but it is also disable only default store.

$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
$productObj = $productRepository->get('sku',true,0,true);
$productObj->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
$productRepository->save($productObj);

Can anyone help? Thanks in advance 🙂

Best Answer

You can use product action class instead of using product repository and load for each product.

private $action;

private $storeManager;

public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\Action $productAction,
    \Magento\Store\Model\StoreManagerInterface $storeManager
) {
    $this->action = $productAction;
    $this->storeManager = $storeManager;
}

public function execute() {
    $productIds = [1,2,3];
    $updateAttributes['status'] = \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED;

    $storeIds = array_keys($this->storeManager->getStores());
    foreach ($storeIds as $storeId) {
        $this->action->updateAttributes($productIds, $updateAttributes, $storeId);
    }
}

Refer what updateAttributes function does git

I have not tested this code but hope this works for you.

Related Topic