Set category product position by programmatically using object manager magento2

        $string = 'sku1,sku2';
        $array = explode(",", $string);
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $i = 1;
        foreach ($array as $id) {
            $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
            $connection = $resource->getConnection();
            $tableName = $resource->getTableName('catalog_product_entity');
            $sql = "Select entity_id FROM " . $tableName . " where sku='$id'";
            //$connection->query($sql);
            $data = $connection->fetchAll($sql);
            $product_id = $data[0]['entity_id'];
            $update_table = $resource->getTableName('catalog_category_product');
            $sqls = "Update " . $update_table . " Set position = '$i' where category_id = '1189' AND product_id='$product_id'";
            // $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/position.log');
            // $logger = new \Zend\Log\Logger();
            // $logger->addWriter($writer);
            // $logger->info($id . ' ==> ' . $sqls);
            $connection->query($sqls);
            $i++;
        }

Comments