0

I would like to set all position sku wise in one specific category using csv
here two column data, sku and position.

So if anyone has an idea for the custom script kindly reply for me

below code

<?php
use Magento\Framework\App\Bootstrap;
include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
    /*
     * Below code used to update category of particular products position 
     */
$csvFile = '../import-cat.csv';
$file = fopen($csvFile, 'r');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $categoryId = 336; //replace with your categoryId
    //$newPosition = 100; //replace with your new position
    $category = $objectManager->get('\Magento\Catalog\Model\CategoryFactory')->create()->load($categoryId);
    $products_po = $category->getProductsPosition();
    //echo "<pre>";
    //var_dump($products_po);
    //die;
    $flag = true;
    $products = array();
    while (($line = fgetcsv($file)) !== FALSE) {      
        if($flag) { $flag = false; continue; }

        $productId = $objectManager->get('Magento\Catalog\Model\Product')->getIdBySku($line[0]);
        //echo $productId."<br>";
        $products[$productId] = $line[1];

    }

    fclose($file);

    $category->setPostedProducts($products);
    $category->save();

exit("<br>Finished.");
    //Enable if you want to see the result
    //foreach($catProduct as $pro){   
        //echo '<pre>';print_r($pro->getData());  
    //}
?>

Thx in forward!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.