Magento 2 and Customer Segmentation: Advanced Targeting Strategies

Magento 2 and Customer Segmentation: Advanced Targeting Strategies

If you're running a Magento 2 store, you already know that not all customers are the same. Some browse but never buy, others make small purchases, and a few are your high-value VIPs. Wouldn't it be great if you could treat each group differently? That's where customer segmentation comes in.

In this post, we'll dive deep into Magento 2's built-in segmentation tools and explore some advanced strategies to take your targeting to the next level. Whether you're new to segmentation or looking to refine your approach, we've got practical examples and code snippets to help you implement these strategies effectively.

Why Customer Segmentation Matters

Customer segmentation is the process of dividing your customer base into groups based on shared characteristics like:

  • Demographics (age, gender, location)
  • Purchase history (frequency, average order value)
  • Behavior (browsing patterns, cart abandonment)
  • Engagement (email opens, loyalty program status)

When done right, segmentation lets you:

  • Send personalized marketing messages
  • Offer targeted promotions
  • Create custom shopping experiences
  • Improve customer retention

Magento 2's Built-in Segmentation Tools

Magento 2 comes with a solid foundation for customer segmentation. Here's how to access it:

  1. Navigate to Customers > Segments
  2. Click Add Segment
  3. Define your segment conditions

For example, to create a segment of customers who spent over $500 in the last 30 days:

1. Name: "High Spenders - Last 30 Days"
2. Conditions:
   - Lifetime Sales Amount > 500
   - Last Order Date is within last 30 days
3. Save and Apply

Advanced Segmentation with Custom Attributes

While the built-in tools are useful, you'll often need to go beyond basic demographics and purchase history. Here's how to create custom customer attributes for more sophisticated segmentation:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/attribute.xsd">
    <attribute code="customer_lifestyle" translate="label" module="Magento_Customer">
        <label>Lifestyle</label>
        <sort_order>100</sort_order>
        <visible>true</visible>
        <system>false</system>
        <forms>
            <form>customer_account_create</form>
            <form>customer_account_edit</form>
            <form>adminhtml_customer</form>
        </forms>
        <backend>Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend</backend>
        <source>Vendor\Module\Model\Customer\Attribute\Source\Lifestyle</source>
        <type>varchar</type>
        <input>select</input>
        <required>false</required>
    </attribute>
</config>

After creating the attribute, you can use it in your segmentation rules just like any built-in attribute.

Behavioral Segmentation with Event Tracking

To create segments based on customer behavior, you'll need to track specific events. Here's how to implement a basic event tracker:

require(['jquery', 'mage/cookies'], function($) {
    $(document).on('click', '.product-item-link', function() {
        var productId = $(this).closest('.product-item').data('product-id');
        var currentProducts = $.mage.cookies.get('recently_viewed');
        currentProducts = currentProducts ? JSON.parse(currentProducts) : [];
        
        if (currentProducts.indexOf(productId) === -1) {
            currentProducts.push(productId);
            $.mage.cookies.set('recently_viewed', JSON.stringify(currentProducts), {path: '/'});
        }
    });
});

You can then create segments based on these tracked behaviors, like "Viewed Product X but Didn't Purchase."

Dynamic Pricing Strategies

One powerful application of segmentation is dynamic pricing. Here's a basic example of how to implement tiered pricing based on customer segments:

<?php
namespace Vendor\Module\Plugin;

use Magento\Customer\Model\Session as CustomerSession;
use Magento\Catalog\Model\Product;

class TieredPricing
{
    protected $customerSession;
    
    public function __construct(CustomerSession $customerSession)
    {
        $this->customerSession = $customerSession;
    }
    
    public function afterGetPrice(Product $product, $price)
    {
        if ($this->customerSession->isLoggedIn()) {
            $customer = $this->customerSession->getCustomer();
            
            // Check if customer is in VIP segment
            if ($customer->getData('is_vip')) {
                return $price * 0.9; // 10% discount for VIPs
            }
        }
        
        return $price;
    }
}

Personalized Email Campaigns

Segmentation shines when combined with email marketing. Here's how to send targeted emails based on segments:

<?php
namespace Vendor\Module\Cron;

use Magento\CustomerSegment\Model\ResourceModel\Segment\CollectionFactory as SegmentCollectionFactory;
use Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory as SubscriberCollectionFactory;
use Magento\Newsletter\Model\QueueFactory;
use Magento\Store\Model\StoreManagerInterface;

class SendSegmentEmails
{
    protected $segmentCollectionFactory;
    protected $subscriberCollectionFactory;
    protected $queueFactory;
    protected $storeManager;
    
    public function __construct(
        SegmentCollectionFactory $segmentCollectionFactory,
        SubscriberCollectionFactory $subscriberCollectionFactory,
        QueueFactory $queueFactory,
        StoreManagerInterface $storeManager
    ) {
        $this->segmentCollectionFactory = $segmentCollectionFactory;
        $this->subscriberCollectionFactory = $subscriberCollectionFactory;
        $this->queueFactory = $queueFactory;
        $this->storeManager = $storeManager;
    }
    
    public function execute()
    {
        $segments = $this->segmentCollectionFactory->create()
            ->addFieldToFilter('is_active', 1);
            
        foreach ($segments as $segment) {
            $subscribers = $this->subscriberCollectionFactory->create()
                ->addFieldToFilter('segment_id', $segment->getId());
                
            if ($subscribers->count() > 0) {
                $queue = $this->queueFactory->create();
                $queue->setTemplateId('segment_specific_template')
                    ->setSubscribers($subscribers)
                    ->setStoreId($this->storeManager->getStore()->getId())
                    ->save();
            }
        }
    }
}

Integrating with Third-Party Tools

While Magento's built-in tools are powerful, you might want to integrate with specialized customer data platforms (CDPs) or marketing automation tools. Here's a basic API integration example:

<?php
namespace Vendor\Module\Model;

use Magento\Customer\Model\CustomerFactory;
use Magento\CustomerSegment\Model\SegmentFactory;
use GuzzleHttp\Client;

class CdpIntegration
{
    protected $customerFactory;
    protected $segmentFactory;
    protected $client;
    
    public function __construct(
        CustomerFactory $customerFactory,
        SegmentFactory $segmentFactory
    ) {
        $this->customerFactory = $customerFactory;
        $this->segmentFactory = $segmentFactory;
        $this->client = new Client(['base_uri' => 'https://api.yourcdp.com/v1/']);
    }
    
    public function syncSegment($segmentId)
    {
        $segment = $this->segmentFactory->create()->load($segmentId);
        $customers = $this->customerFactory->create()
            ->getCollection()
            ->addFieldToFilter('segment_id', $segmentId);
            
        $customerData = [];
        foreach ($customers as $customer) {
            $customerData[] = [
                'email' => $customer->getEmail(),
                'segment' => $segment->getName(),
                'attributes' => $customer->getData()
            ];
        }
        
        $this->client->post('segments/update', [
            'json' => [
                'segment_id' => $segmentId,
                'customers' => $customerData
            ]
        ]);
    }
}

Measuring Segmentation Success

To ensure your segmentation strategies are working, track these key metrics:

  • Segment-specific conversion rates: Are customers in your segments converting at higher rates?
  • Average order value by segment: Are your high-value segments spending more?
  • Email engagement rates: Do segmented emails get better open and click rates?
  • Customer lifetime value: Are segmented customers more valuable over time?

Here's how to create a simple dashboard to track these metrics:

<?php
namespace Vendor\Module\Block\Adminhtml\Dashboard;

use Magento\Backend\Block\Template;
use Magento\Reports\Model\ResourceModel\Customer\CollectionFactory as CustomerCollectionFactory;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;

class SegmentPerformance extends Template
{
    protected $customerCollectionFactory;
    protected $orderCollectionFactory;
    
    public function __construct(
        Template\Context $context,
        CustomerCollectionFactory $customerCollectionFactory,
        OrderCollectionFactory $orderCollectionFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->customerCollectionFactory = $customerCollectionFactory;
        $this->orderCollectionFactory = $orderCollectionFactory;
    }
    
    public function getSegmentPerformance($segmentId)
    {
        $customers = $this->customerCollectionFactory->create()
            ->addFieldToFilter('segment_id', $segmentId);
            
        $orders = $this->orderCollectionFactory->create()
            ->addFieldToFilter('customer_id', ['in' => $customers->getAllIds()]);
            
        return [
            'customer_count' => $customers->count(),
            'order_count' => $orders->count(),
            'average_order_value' => $orders->count() > 0 ? $orders->getTotals('grand_total') / $orders->count() : 0,
            'conversion_rate' => $customers->count() > 0 ? ($orders->count() / $customers->count()) * 100 : 0
        ];
    }
}

Best Practices for Effective Segmentation

To get the most out of your segmentation efforts:

  1. Start simple: Begin with basic segments like new vs. returning customers before moving to more complex groupings.
  2. Use multiple criteria: Combine demographic, behavioral, and transactional data for richer segments.
  3. Keep segments updated: Customer behavior changes, so regularly refresh your segments.
  4. Test and optimize: Try different segment definitions and measure what works best.
  5. Respect privacy: Be transparent about data collection and use, especially with GDPR and other regulations.

Conclusion

Customer segmentation in Magento 2 is a powerful tool that goes far beyond simple demographic groupings. By leveraging both built-in features and custom implementations, you can create highly targeted experiences that drive engagement, increase conversions, and boost customer loyalty.

The examples in this post should give you a solid foundation to start implementing more advanced segmentation strategies in your Magento 2 store. Remember that the most effective segmentation is an ongoing process of testing, measuring, and refining based on real customer behavior and business results.

Have you implemented any interesting segmentation strategies in your Magento store? Share your experiences in the comments!