Bugfixes: Product category position lost during import

March 16, 20122 min read
Bugfixes: Product category position lost during import

There is a strange bug in Magento version 1.6. It happened when you define products order within category and then re-import the products. After that defined positions are reverted to 1.

The problem is in the file: app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php, function _saveProductCategories().

Lets study the code.
[cc lang='php' ]
if ($categoriesData) {
$categoriesIn = array();
$delProductId = array();

foreach ($categoriesData as $delSku => $categories) {
$productId = $this->_newSku[$delSku]['entity_id'];
$delProductId[] = $productId;

foreach (array_keys($categories) as $categoryId) {
$categoriesIn[] = array('product_id' => $productId, 'category_id' => $categoryId, 'position' => 1);
}
}
if (Mage_ImportExport_Model_Import::BEHAVIOR_APPEND != $this->getBehavior()) {
$this->_connection->delete(
$tableName,
$this->_connection->quoteInto('product_id IN (?)', $delProductId)
);
}
if ($categoriesIn) {
$this->_connection->insertOnDuplicate($tableName, $categoriesIn, array('position'));
}
}

As you see we set position=1, which is correct for new imported products. However then we perform insertOnDuplicate(), and if the position for this category/product already specified, it replace the position with 1 as well.

To fix this issue, you have to replace this line:

[cc lang='php' ]
if ($categoriesIn) {
$this->;_connection->;insertOnDuplicate($tableName, $categoriesIn, array('position'));
}

with the following:
[cc lang='php' ]
if ($categoriesIn) {
$this->_connection->insertOnDuplicate($tableName, $categoriesIn, array('category_id'));
}

Thus if the product position already exists in the database it will not be updated.

PLEASE BACKUP THE FILES AND DATABASE BEFORE MAKING ANY CHANGES, SERIOUSLY.

Need help with your store?

We build and support online stores and B2B portals on Laravel and Magento, and move stores from Magento to Laravel without losing rankings.