Programmatically Assign Customer Group for Selected Category Product Order
-
22-10-2019 - |
Question
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.
Solution 2
I create a observer for checkout_onepage_controller_success_action and add the below code, and its get works well.
$mem_catid = 8; //CATEGORY ID products to filter
$_customerId = Mage::getSingleton('customer/session')->getCustomerId();
$lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
$order = Mage::getSingleton('sales/order');
$order->load($lastOrderId);
$allitems = $order->getAllItems();
foreach($allitems as $item)
{
$product = Mage::getModel('catalog/product')->load($item->getProductId());
$categoryIds = $product->getCategoryIds();
if (in_array($mem_catid, $categoryIds)) {
$mem_group_id = $item->getSku(); // $item->getSku() is customer group name
$customer_detail = Mage::getSingleton('customer/session')->getCustomer();
$customer_detail->setGroupId($mem_group_id);
$customer_detail->save();
}
}
OTHER TIPS
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();
}