I would like to customize the product listings cache for unlogged customers in Magento 2 so that the order of products is sorted based on a value stored in a cookie. Currently, Magento uses a single product listings cache for all unlogged customers. However, I want to cache the product listings based on the cookie value. For example, if the cookie value is 1, I want to use one cache with a specific product sort order, and if the cookie value is 2, I want to use another cache with a different product sort order. I already have the logic for custom sorting implemented, but the cache prevents me from utilizing it. How can I achieve this?
1 Answer 1
I got it. Magento uses the Magento\Framework\App\PageCache\Identifier::getValue method to get the page cache ID. The value from the X-Magento-Vary cookie is taken from there to distinguish the cache, and the value in the X-Magento-Vary cookie comes from the Magento\Framework\App\Http\Context data field.
So, just add:
 if (!$this->customerSession->isLoggedIn()) {
 $this->httpContext->setValue(
 'my_name',
 'my_value', 
 'default_value'
 );
 }
Explore related questions
See similar questions with these tags.