Comment utiliser les groupes de clients de Magento 2 pour des promotions et des contenus ciblés
How to Use Magento 2's Customer Groups for Targeted Promotions and Content
If you’re running a Magento 2 store, groupe de clientss are one of those underused fonctionnalités that can deliver outsized results. Think of them as neatly labeled buckets — you can serve different prixs, promotions, and even entirely different contenu to each bucket. In this post I’ll walk you through advanced configuration d'administration, practical segmentation strategies, code exemples you can paste into a module or data correctif, integration conseils for marketing automation, concrete B2B vs B2C cas d'utilisation (loyalty, tiered tarification), and comment measure ROI so you can iterate properly. I’ll keep the tone relaxed — like we’re pairing a coffee and working through it together.
Why groupe de clientss matter
Customer groups let you classify visiteurs and clients (e.g., Guests, General, Wholesale, VIP). That classification can then be used by:
- Catalog Price Rules and Cart Price Rules (apply discounts by group)
- Tax rules (tax class per group)
- Visibility control for contenu and blocks
- Targeting in marketing automation and segmentation feeds
- Reporting and ROI measurement
Used well, groups let you run hyper-targeted promotions and personalize contenu without building dozens of custom vitrines.
High-level stratégie: who to put in which group
Start with a simple taxonomy and expand. Example starter groups:
- Guests (non-logged visiteurs)
- Retail / General consommateurs
- Wholesale / Trade / B2B buyers
- Loyalty tiers (Silver, Gold, Platinum) — created once you have repeat purchase data
- Test / Internal (for QA and test rules)
Segmentation ideas for promotions:
- Cart-valeur based promotions for high-valeur segments
- Cross-sell bundles for wholesale vs retail (different margin tolerance)
- Tiered free shipping thresholds per loyalty tier
Advanced technical configuration in Magento 2 admin
Create and configure groupe de clientss
Go to Customers > Customer Groups > Add New Customer Group. Key champs:
- Group Name: obvious but use a naming convention (retail, wholesale, loyalty_gold)
- Tax Class: map groups to règle fiscales (important for B2B where you may have tax-exempt accounts)
Pro conseil: Keep an internal “Test” group to pavis promotions without affecting real clients.
Use Catalog Price Rules for group-based catalog discounts
Admin path: Marketing > Catalog Price Rules > Add New Rule.
Important champs:
- Rule Name and Description
- Website scope
- Customer Groups: select the group(s) you want
- Conditions: SKU, attribute set, category, etc.
- Actions: percentage/amount discount, apply to matching products
Après saving, be sure to click "Save and Apply" or réindexer rules so they take effect on the frontend catalog.
Use Cart Price Rules for paiement-level promotions
Admin path: Marketing > Cart Price Rules. Here you can create coupons scoped to specific groups and set usage limits per client.
Example cas d'utilisation: 10% off for loyalty_gold on commandes over $150 usable once per client. Vous pouvez test by creating a coupon with a specific code reserved for that group.
Programmatic exemples — show me code
Below are practical code snippets you can use in a custom module or data correctif. These are réel patterns I use when automating group creation, assigning groups, and creating rules. I’ve kept them minimal but practical.
1) Add a groupe de clients programmatically (Data Patch)
Create a data correctif under Setup/Patch/Data/CreateCustomerGroup.php:
moduleDataSetup = $moduleDataSetup;
$this->groupFactory = $groupFactory;
}
public function apply()
{
$this->moduleDataSetup->getConnection()->startSetup();
$group = $this->groupFactory->create()->load('loyalty_gold', 'customer_group_code');
if (!$group->getId()) {
$group->setCode('loyalty_gold')
->setTaxClassId(3) // adjust tax class id as necessary
->save();
}
$this->moduleDataSetup->getConnection()->endSetup();
}
public static function getDependencies() { return []; }
public function getAliases() { return []; }
}
That will create a group named loyalty_gold. Vous pouvez adapt the code to run for mulconseille groups or to update tax class mapping.
2) Assign a client to a group on registration (Observer exemple)
Use event client_register_success to change the group basé sur criteria (e-mail domain, referral, or signup flow).
customerRepository = $customerRepository;
}
public function execute(Observer $observer)
{
$customer = $observer->getEvent()->getCustomer();
$email = $customer->getEmail();
// Example rule: any corporate email with @company.com goes to wholesale
if (strpos($email, '@company.com') !== false) {
$customer->setGroupId(3); // wholesale group id
$this->customerRepository->save($customer);
}
}
}
Tip: Use data correctifs to create the mapping between group code and id during module install, so you never hardcode numeric ids.
3) Create a Cart Price Rule programmatically
Quick exemple using the SalesRule model (use with DI and prefer repository in production):
ruleFactory->create();
$rule->setName('10% for Loyalty Gold')
->setDescription('Auto-created rule for loyalty gold')
->setFromDate('')
->setToDate('')
->setIsActive(1)
->setCouponType(2) // Specific coupon
->setCouponCode('LOYALTY10')
->setUsesPerCustomer(1)
->setCustomerGroupIds([5]) // group id array
->setSimpleAction('by_percent')
->setDiscountAmount(10)
->setStopRulesProcessing(0);
$this->ruleRepository->save($rule);
Assurez-vous to clear caches and réindexer as needed. In production, wrap this behind a data correctif or a CLI command so you can version control it.
4) Show different frontend contenu by group
In a .phtml template, check the session group id and render accordingly:
<?php
/** @var \Magento\Customer\Model\Session $customerSession */
$customerSession = $block->getCustomerSession();
$groupId = $customerSession->getCustomerGroupId();
if ($groupId == 3) : ?>
<div class="promo-wholesale">Special wholesale catalog here</div>
<?php elseif ($groupId == 5) : ?>
<div class="promo-loyalty">Exclusive deals for Loyalty members</div>
<?php else : ?>
<div class="promo-retail">Shop new arrivals</div>
<?php endif; ?>
Better approche: use a classe de bloc to fetch group id and inject into the template to keep presentation thin.
5) Serve bloc CMS per group using layout XML
Create a block and programmatically set the bloc CMS identifier basé sur group id in Block class. Example Block méthode:
public function getCmsIdentifierByGroup()
{
$groupId = $this->customerSession->getCustomerGroupId();
switch ($groupId) {
case 3:
return 'cms_wholesale_banner';
case 5:
return 'cms_loyalty_banner';
default:
return 'cms_default_banner';
}
}
Then use $block->getCmsIdentifierByGroup() in phtml to render the correct block with createBlock('Magento\Cms\Block\Block')->setBlockId($identifier).
Integration with marketing automation and advanced promo modules
Customer groups are a great join-point — you can export clients by group to your marketing automation platform and trigger tailored campaigns.
Example: export clients via API REST filtreed by group
Magento REST endpoint for clients with rechercheCriteria:
curl -X GET "https://yourstore.com/rest/V1/customers?searchCriteria[filter_groups][0][filters][0][field]=group_id&searchCriteria[filter_groups][0][filters][0][value]=5&searchCriteria[filter_groups][0][filters][0][condition_type]=eq" -H "Authorization: Bearer <admin_token>"
That call returns clients in group id 5. Vous pouvez then feed this into your e-mail platform or CRM, mapping champs and adding tags like loyalty_gold.
Automate rule activation via cron or external scheduler
Need a short weekend sale for VIP group only? Create the rule programmatically and toggle is_active using a tâche cron. Example partial cron task code:
public function execute()
{
$rule = $this->ruleRepository->getById($ruleId);
$rule->setIsActive(1);
$this->ruleRepository->save($rule);
}
Using cron or CI pipeline to enable/disable promotions reduces manual erreurs.
Connect to advanced promotion modules
Magento’s ecosystem has modules for loyalty programs, dynamic tarification, and promotions orchestration. The integration pattern is usually:
- Export client list (by group) to the promo engine or import groupe de clients attributes into the engine.
- Use webhooks or API to push events (commande placed, points earned) back to Magento to change group (e.g., move a client to Silver/Gold).
- Keep a small piece of logic in Magento to guard entreprise-critical decisions (final prix calculation, tax handling).
Pro conseil: prefer pushing only identifiers and minimal attributes to the external system, and use that system to run heavy segmentation/automation. Use Magento to enforce final prixs and commande validation.
Concrete cas d'utilisation: B2B vs B2C, loyalty programs, and tiered tarification
B2B
B2B stores often need wholesale tarification, net terms, or tax-exempt handling. Customer groups map neatly to B2B account types:
- Group: Trade — Catalog Price Rule for wholesale catalog tarification
- Group: Net30 — different paiement flow or payment options basé sur group
- Group: TaxExempt — map to a tax class with 0% and have admin verify entreprise documents
Example: create a Catalog Price Rule giving 20% off to wholesale group for products in category "bulk-packages". Combine with a Cart Price Rule that offers free shipping for commandes above a certain quantity.
B2C
For consommateur stores, groups let you run loyalty tiers and special incentives:
- New clients get a welcome coupon exclusive to group "new_client"
- Repeat clients move to loyalty_gold and see personalized banners and higher discounts
Loyalty program (automated)
Workflow exemple to earn tiers:
- Customer places commandes tracked by events. Orders are sent to an external loyalty engine.
- Engine evaluates points and triggers an API call to Magento to set the group id (e.g., move to loyalty_gold).
- Magento then shows loyalty blocks and enables loyalty-specific Cart/Catalog Price Rules.
Implement the group change with a secure point d'accès API in Magento that validates the request. Example minimal contrôleur skeleton:
class Api\Controller\V1\SetGroup extends \Magento\Framework\App\Action\Action
{
public function execute()
{
$customerId = (int)$this->getRequest()->getParam('customer_id');
$groupId = (int)$this->getRequest()->getParam('group_id');
// Validate API key, payload signature, etc.
$customer = $this->customerRepository->getById($customerId);
$customer->setGroupId($groupId);
$this->customerRepository->save($customer);
$this->getResponse()->representJson(json_encode(['success' => true]));
}
}
Tiered tarification
Vous pouvez implement tiered tarification using Catalog Price Rules or the Advanced Pricing fonctionnalités (group prix attribute on product level). For large catalogs, prefer Catalog Price Rules because they’re easier to maintain at scale.
Measuring ROI and analytics for segmented campaigns
Measurement is the most important étape. Si vous can’t measure the incremental lift from client-group-targeted promotions, you’re flying blind.
Quick analytics checklist
- Track coupon redemptions per client_group_id
- Report on revenue, average commande valeur (AOV), and conversion rate by group
- Attribute promotional cost (discount) to commandes and compute net revenue
- Use UTM paramètres on group-specific landing pages to measure campaign source in GA
Sample SQL: revenue by groupe de clients (simple)
SELECT
cg.customer_group_code,
SUM(o.base_grand_total) AS total_revenue,
COUNT(o.entity_id) AS orders_count,
AVG(o.base_grand_total) AS avg_order_value
FROM
sales_order AS o
LEFT JOIN
customer_group AS cg ON o.customer_group_id = cg.customer_group_id
WHERE
o.created_at >= '2025-01-01'
GROUP BY
o.customer_group_id;
This vous donne a raw look at revenue and AOV per group. For campaign-level attribution, join sales_commande with salesrule_coupon and salesrule_redemption tables or use commande-level code promos.
Compute ROI for a group-specific campaign
Simple ROI formula for a promotion:
ROI = (IncrementalRevenue - PromotionCost) / PromotionCost
How to estimate:
- IncrementalRevenue: revenue from coupon redemptions in the target group minus baseline revenue (e.g., same period previous week without promos)
- PromotionCost: sum of discounts given (sum of discount_amount on commandes) + marketing spend (ad cost, e-mails)
Example calculation (very simplified):
IncrementalRevenue = $10,000
PromotionCost (discounts) = $1,500
Marketing spend = $500
PromotionCostTotal = $2,000
ROI = (10,000 - 2,000) / 2,000 = 4 (400%)
Important: use A/B test where possible. Compare a segment exposed to the promotion with a control group that does not get it (or gets a different promo). That helps separate seasonality and other effects.
Tracking utilisateur journeys by group
Tag pages and events with the groupe de clients (only for logged utilisateurs). Par exemple, push client_group to a dataLayer event so your analytics platform can segment sessions. Example JavaScript snippet to push group id:
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'customerInfo',
'customerGroupId': '5',
'customerGroupName': 'loyalty_gold'
});
With that, generate funnels and conversion rapports per group in Google Analytics or your BI tool.
Operational conseils and pitfalls
- Don’t create too many groups at first — keep it manageable. Each group increases admin complexity and test surface.
- Always have a test group and test accounts for each group so you can pavis prixs and contenu without déployering site-wide changes.
- Be careful with indexeurs: after programmatic changes to tarification rules or products, réindexer and flush caches.
- Audit code promos and rule overlaps: rules can stack or override depending on “stop rules processing”.
- Document the life cycle of a group — who can change it and under what circumstances (e.g., automated move to loyalty only after confirmed payment).
Examples of small automation flows
Auto-move client to loyalty_gold after threshold
Pseudo-flow:
- Daily cron runs retrieves total lifetime spend per client.
- If spend > threshold (e.g., $1,000), call Magento API to set group_id to loyalty_gold.
- Send an e-mail via your marketing platform to congratulate them and enable the loyalty-specific coupon in Magento.
Cron sample: set group basé sur lifetime commande valeur (pseudo)
// Pseudo code outline:
$customers = $this->customerCollectionFactory->create();
foreach ($customers as $customer) {
$lifetime = $this->getLifetimeValueForCustomer($customer->getId());
if ($lifetime >= 1000 && $customer->getGroupId() != $goldGroupId) {
$customer->setGroupId($goldGroupId);
$this->customerRepository->save($customer);
}
}
Assurez-vous to throttle and run during low traffic windows. Keep logs and notifications for failures.
Testing and QA
Test every combo: group + prix rule + catalog + paiement. Here’s a short checklist:
- Create accounts in each target group and password-manage them for QA
- Pavis catalog prixs as a logged-in utilisateur per group
- Run through paiement with coupons and validate discount computations and tax behavior
- Ensure e-mails (commande, facture) reflect correct tarification and tags
- Validate analytics and ensure group id is pushed to your dataLayer
Putting it all together: a sample campaign
Let’s run a hypothetical campaign for loyalty_gold:
- Goal: increase repeat purchases among loyalty_gold by 20% this quarter.
- Audience: clients with group loyalty_gold (1000 clients).
- Promotion: 10% off catalog + free shipping over $75, coupon LOYALTY10 active for 30 days.
- Execution étapes:
- Programmatically create and activate Cart Price Rule with coupon LOYALTY10 for loyalty_gold and set start/end date.
- Export loyalty_gold clients via REST and import into marketing automation to schedule the launch e-mail.
- Push a frontend banner only visible to loyalty_gold (bloc CMS rendered by group).
- Track coupon redemptions and commandes, and compute incremental revenue vs. baseline.
- Measurement:
- Orders with coupon LOYALTY10 by group
- Revenue and AOV uplift
- Cost of discounts + e-mail/ad spend
Résumé and bonnes pratiques checklist
Short checklist before you launch:
- Define a simple group taxonomy; don’t overcomplicate
- Use data correctifs or versioned scripts to create groups and rules — keep everything in VCS
- Prefer exporting minimal client info and doing heavy segmentation in your marketing tool
- Test, test, test. Always have a test account per group
- Measure: coupon redemptions, commandes, revenue by group. Compute ROI and iterate
- Keep entreprise logic simple in Magento (prix calc, tax). Offload orchestration to specialized systems
Why Magefine clients should care
Si vous host with Magefine or use Magefine extensions (or plan to), think about integnote these group flows into your déploiement pipeline. Versioned data correctifs, scheduled crons, and monitorable APIs make automation safe. Use your hosting provider’s staging and snapshot capabilities to pavis promotions and prix changes before you flip them live.
Final notes
Customer groups in Magento 2 are low-friction, high-impact. With a handful of groups, some disciplined automation, and a clear measurement plan, you can run promotions that feel personal and convert better. If you’d like, I can provide a downloadable exemple module scaffold that includes a data correctif to create groups, a cron to sync lifetime spend, and sample Cart Price Rule creation — or walk through a tailored plan for your catalog and margins.
Happy building — and ping me if you want the sample module scaffold or help wiring analytics for ROI tracking. If you’re running on magefine.com hosting, use a staging snapshot to test these flows before you go live.