Magento 2 – How to Update Product Price by Website or Store ID

magento-2.1magento2magento2.2pricestores

I try to programmatically update product price for different website in magento2.

This blow code is working but It will update main website price only, I need to update different website price using different website id.

<?php
error_reporting(1);
ini_set('max_execution_time', 0);
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product_id = 7878;
$price = "3.99";
$productFactory = $objectManager-
>get('\Magento\Catalog\Model\ProductFactory');
$product = $productFactory->create()->load($product_id);
$product->setPrice($price);
$product->save();
?>

How can I load website?

Best Answer

You need to set store id when you load product object, Your final code look like this

$storeId = '1'; //Store ID
$product_id = 7878;
$price = "3.99";
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
$product = $productFactory->create()->setStoreId($storeId)->load($product_id);
$product->setPrice($price);
$product->save();

Also, you need to change price scope.

Go to System->Configuration->Catalog->Catalog Price Scope

Then in the tab "Price", set price scope to "Website" instead of global.

Related Topic