monak83
monak83

Reputation: 125

Magento: assign all product to Default Category

How can I assign all my product to default category?

I would not loose the actual category assigned but I would add also default category.

On this way PRODUCT A that has Category 1 will have also Default Category and PRODUCT B that have any category assigned will have only Dafault category.

Thanks

Upvotes: 2

Views: 1398

Answers (2)

Alex Ivanov
Alex Ivanov

Reputation: 436

You can do that using this custom script:

<?php
require_once 'app/Mage.php';
Mage::app();
$default_category_id = [your default category id];
$db = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql = "SELECT product_id FROM catalog_category_product WHERE category_id != ?";
$pIds = $db->fetchAll($sql, array($default_category_id));
foreach($pIds as $pid) {
   $sql = "INSERT INTO catalog_category_product (category_id, product_id, position) VALUES (?,?,1)";
   $db->query($sql, array($default_category_id, $pid));
}
?>

Hope it will help you.

Upvotes: 1

Javier C. H.
Javier C. H.

Reputation: 2123

I always try to avoid running direct SQL queries when you can use the existing models. This is how I would do it:

<?php
require_once 'app/Mage.php';
Mage::app();

$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($store_id) // Or use the default Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID 
->addAttributeToSelect('*'); 
// You may need to specify a limit if you have too many products with: ->setPageSize(NUMBER_OF_PRODUCTS)

$newCategories = array(12345); // Put as much categories as you want to add

foreach ($collection as $product) {
    // array_merge: To keep the existing ids
    // array_unique: to avoid assigning the same category twice
    $product->setCategoryIds(
    array_unique(array_merge($product->getCategoryIds(), $newCategories))
    );
    $product->save();
}

You will probably need to reindex afterwards (if you have disabled update on save in your reindex settings) in order to the changes to take effect.

Upvotes: 1

Related Questions