简体   繁体   中英

Magento2 How to update product information programmatically (PHP Script)?

I tried to update all product information by product id but it's not working for me for all information. With below code "SKU" update successfully but unable to update other information like product name and other custom attribute value.

How can I update all the information about the products using PHP script?

$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
$product = $productFactory->create()->setStoreId($storeId)->load($product_id);
$product->setStatus(1);
$product->setName('test pr 123');
$product->setSku('test sku');
$product->setDescription("new product description.");
$product->setShortDescription("new short description.");
$product->save();

Here I'm adding a script hope this will help and solve your problem

use Magento\Framework\App\Bootstrap;
require __DIR__ . 'app/bootstrap.php';

$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$instance = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$product_collections = $instance ->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collections = $product_collections->create();
foreach ($collections as $product) {
    $id = $product->getId(); 
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($id);
    $product->setWebsiteIds(array(1));
    $product->save();
    echo $id.'-';
}

Add your attribute which you need to update in code

If you just want to override some attribute values, you should use the addAttributeUpdate function. With that you can also update attribute values for different store views.

I use a kind of this code to update my products descriptions etc. for several stores.

    $productRepository = $objectManager->get('Magento\Catalog\Model\ProductRepository');

    // YOU WANT TO LOAD BY ID?
    $id = "YOUR ID HERE";
    // YOU WANT TO LOAD BY SKU?
    $sku = "YOUR SKU HERE";

    if($id) {
        $product = $productRepository->getById($id);
    }
    if($sku) {
        $product = $productRepository->get($sku);
    }



    $shortDescriptionAttributeCode = "short_description";
    $descriptionAttributeCode      = "description";

    $shortDescriptionAttributeValue = "YOUR NEW VALUE";
    $descriptionAttributeValue      = "YOUR NEW VALUE";


    $product->addAttributeUpdate($shortDescriptionAttributeCode, $shortDescriptionAttributeValue, 0);
    $product->addAttributeUpdate($descriptionAttributeCode, $descriptionAttributeValue, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM