How do I get the customer segments associated with current logged in customer.
1 Answer
We can get matched segments of a customer directly from customer session, these are compiled during reindexing and associated to the customer while it's session is created. So, we can get it from customer session object [Magento\Customer\Model\SessionFactory
]
$matchedCustomerSegments = $this->_customerSessionFactory->create()->getCustomerSegmentIds()
With above code you'll get array of the website ids in the first index and matched segments corresponding to them. Such as below;
Array
(
[1] => Array
(
[0] => 1
[1] => 2
)
)
In above case the customer has been matched to segment_ids 1 and 2 corresponding to website_id 1.
Also if you want to get whether the customer has matched with a specific segment instead of segment_id you can use segment collection [Magento\CustomerSegment\Model\ResourceModel\Segment\Collection
] to get the data as following;
$matchedCollection = $this->_segmentModelCollection->addFieldToFilter(
'segment_id',
[
['1','2']
])->addFieldToFilter(
'name',
'Segment Name'
);