0

I'm running an automatic php import file in order to update all products in Magento 2.2. More precisely the script loads the product, then, if it exists, updates its informations and in the end saves it. There is my problem: I try to update its meta title but the method simply doesn't work. Here is my code:

$product1 = $objectManager->get('Magento\Catalog\Model\Product')->getIdBySku($sku);
if($product1) {
    $pid=$product1;

    $product_n1=$objectManager->create('Magento\Catalog\Model\Product')->load($pid);
    $product_n1->setName(trim($importProduct[0])); // Name of product_n1
    $product_n1->setCategoryIds(array($category_id));
    $product_n1->setDescription(trim($descr));
    $product_n1->setShortDescription(trim($shortDesc));
    $metatitle =trim($importProduct[0]).' - Company name';
    $product_n1->setMetaTitle($metatitle);
    $metakey[]=$importProduct[0];
    $metakey[]= trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($importProduct[0]))))));
    $metakey[]=trim(preg_replace('#[^0-9a-z]+#i', '-', $importProduct[0]));
    $meta_str=implode(',',$metakey);
    $product_n1->setMetaKeyword(trim($meta_str));
    $product_n1->setMetaDescription(trim(strip_tags($descr)));
    $product_n1->setStatus(1); // Status on product_n1 enabled/ disabled 1/0
    $product_n1->setWeight(10); // weight of product_n1
    $product_n1->setVisibility(4); // visibilty of product_n1 (catalog / search / catalog, search / Not visible individually)
    $product_n1->setTaxClassId(2); // Tax class id
    $product_n1->setPrice($importProduct[1]); // price of product_n1
    $product_n1->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
            'qty' => 1000,
            'min_sale_qty' => $pkgqty_int,
            'qty_increments' => $pkgqty_int,
            'enable_qty_increments' => 1
        )
    );

    $product_n1->save();
}

I don't understand what's wrong in my code. Thank you all for the support

Nicola
  • 1
  • 1

1 Answers1

0

You need a repository to save the product in magento 2.x

protected $productRepository;

public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
){
    $this->productRepository = $productRepository;
}

public function execute($id, $metaTitle) 
{
    $product = $this->productRepository->getById($id, true);
    $product->setMetatTitle($metaTitle);
    $product = $this->productRepository->save($product);
}
Kervin Ramen
  • 2,575
  • 2
  • 24
  • 22