Programmatically Assign Customer Group for Category Product Order

customer-groupproduct

I want to assign a customer group for the customers, who have placed the order from selected category or particular products.

I have a category name grouper. In this category, I have some products with SKU names x1,x2 and x3.

I also have the Customer Group named same as product of this category. ie x1,x2 and x3 and these products can only be purchased alone.

So when I purchased or place order x1 then the customer group for this customer should assign as x1. When the order is success the group should assign.

Any ideas?

Thanks in advance.

Best Answer

You don't make it clear at what point you want to do this in the process, but you should be able to do something like the following:

// array of special products
$products = array(1,2,3,4);
// flag
$changeGroup = false;
// group to move customer to
$groupId = 1234;

$customer = Mage::getModel('customer/customer')-loadByEmail($email);

$orders = Mage::getResourceModel('sales/order_collection')
->addFieldToSelect('*')
->addFieldToFilter('customer_id', $customer->getId())
->addAttributeToFilter('state', array('neq' => Mage_Sales_Model_Order::STATE_CANCELED));

foreach ($order->getAllItems() as $orderItem) {
    if (in_array($orderItem->getProductId(), $products)) {
        $changeGroup = true;
    }
}

if ($changeGroup == true) {
    $customer->setGroupId($groupId);
    $customer->save();
}
Related Topic