How can products be assigned to multiple stores programmatically in Magento 2?

Magentocommerce
How can products be assigned to multiple stores programmatically in Magento 2?

Let’s say you have a Magento multi-website/store installation and you want to assign the products of a particular category to the new store. I wrote a few lines of code to accomplish this.

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$categoryIds = [41]; // Category IDs whose products you want to assign
foreach ($categoryIds as $categoryId) {
    $category = $objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
    $productCollection = $category->getProductCollection();
    foreach ($productCollection as $product) {
        $productId = $product->getId();
        $websiteIds = $product->getWebsiteIds();
        $storeIds = $product->getStoreIds();
        if (!in_array(1, $websiteIds)) {
            continue;
        }
        $websiteIds[] = 2;
        $websiteIds = array_unique($websiteIds);
        if (in_array(2, $storeIds)) {
            continue;
        }
        $storeIds[] = 2;
        $storeIds = array_unique($storeIds);
        $product->setWebsiteIds($websiteIds);
        $product->save();
        // Copy the details of the products to the new store
        $newProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($productId)
            ->setStoreIds($storeIds)
            ->save();
        echo "Done : #$productId";
        echo '<br>';
    }
}

You can use this piece of code wherever you want in Magento 2. For example, you can use it as a standalone script to update a bunch of products in the /pub folder. Or, you can use it as a product save observer. It’s your call!

This may not be the most optimized solution, but it did the trick for me.

Leave a Reply

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

17 + 5 =

2hats Logic HelpBot