Add Items to Category Programmatically in Magento

The code on the bottom will take the following array:

$categories = array(
#   "nickname" => category_id,
    "Eyeliner" => 107,
    "Lipstick" => 108,
    "General" => 18,
#   etc.
);

The $lineItems array contains a line of category+sku-items in the format “CategoryNick SKU1 SKU2 SKU3.” CategoryNick is matched against the $categories array above to figure out the Magento category ID. If the product is already in the category, it doesn’t do anything. The product will retain the categories it is already associated with rather than dropping the existing category associations.

$lineItems = Array();
$lineItems[] =     "Eyeliner 7897";
$lineItems[] =     "Eyeliner 7898 7772 7771 7770";
$lineItems[] =     "Lipstick 7909-15 7909-16 7939 7941 7984";
$lineItems[] =     "General 7940"; 

This is the full code. It should be placed in a /filename.php file and visited at /filename.php – Make a backup of your database before using this (and daily!) Don’t keep executable PHP files hanging around after use. If you need to, make sure the permissions are 600 or 700 and NOT world-writable or rename to .phps so they aren’t executable by web

<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
Mage::app();

# assign duct tape to all categories
function FindBySku($sku) {
    return Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
}

function AddToCategory($product, $newcat, $save=false) {
    $cats = $product->getCategoryIds();

    # Don't double categories
    if (in_array($newcat, $cats)) return;

    $cats[] = $newcat;

    $product->setCategoryIds($cats);
    if ($save) return $product->Save();
}

# CHANGE ME
# 3 categories nicknamed and linked to respective Magento IDs
$categories = array(
    "Eyeliner" => 107,
    "Lipstick" => 108,
    "General" => 18,
);

# CHANGE ME
# Add 5 items to the Eyeliner category (107), 5 to Lipstick and 1 to General.
$lineItems = Array();
$lineItems[] =     "Eyeliner 7897";
$lineItems[] =     "Eyeliner 7898 7772 7771 7770";
$lineItems[] =     "Lipstick 7909-15 7909-16 7939 7941 7984";
$lineItems[] =     "General 7940"; 

foreach($lineItems as $line) {
    $pieces = explode(' ', $line);
    $cat = $pieces[0];

    #$skus = implode(' ', $pieces);
    #$skus = substr($skus, strpos($skus, ' ')+1, strlen($skus) - strlen($cat));
    # $cat is the category NickName and $skus is a space-delimited list of SKU #s

    $skus = array_slice($pieces, 1);
    # $cat is the category NickName and $skus is an array of SKU numbers

    if (array_key_exists($cat, $categories) && $categories[$cat] != 0) {
        $cat_id = $categories[$cat];
        echo "Adding to category $cat (id = $cat_id)\n";
        echo '\tAdding ' . sizeof($skus) . " SKUs\n";
        #$item_skus = explode(" ", $skus);
        $i = 0;

        foreach($skus as $sku) {
            $product = FindBySku($sku);
            if (!$product) {
                echo "** ERROR: NO PRODUCT FOUND SKU=$sku\n";
                continue;
            }
            AddToCategory($product, $cat_id, true);
            ++$i;
            echo "\tadded $sku to $cat ";
        }

        echo "\nTOTAL $i/" . sizeof($skus) . " items to $cat\n\n";
    } else {
        echo "** ERROR: CANNOT FIND CATEGORY '$cat'\n\n";
    }
}

?>                            

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>