skip to Main Content

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('MagentoCatalogModelProductFactory');
$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();

2

Answers


  1. Here I’m adding a script hope this will help and solve your problem

    use MagentoFrameworkAppBootstrap;
    require __DIR__ . 'app/bootstrap.php';
    
    $params = $_SERVER;
    $bootstrap = Bootstrap::create(BP, $params);
    $objectManager = $bootstrap->getObjectManager();
    $instance = MagentoFrameworkAppObjectManager::getInstance();
    $state = $objectManager->get('MagentoFrameworkAppState');
    $state->setAreaCode('adminhtml');
    $product_collections = $instance ->get('MagentoCatalogModelResourceModelProductCollectionFactory');
    $collections = $product_collections->create();
    foreach ($collections as $product) {
        $id = $product->getId(); 
        $product = $objectManager->create('MagentoCatalogModelProduct')->load($id);
        $product->setWebsiteIds(array(1));
        $product->save();
        echo $id.'-';
    }
    

    Add your attribute which you need to update in code

    Login or Signup to reply.
  2. 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('MagentoCatalogModelProductRepository');
    
        // 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search