I need to get the customer id of the user that is logged in. Using the following code it works fine for blocks where cache is disabled. But when there's a cached block on the page, it's null. Even if the customer is logged in. It is intended behavior for the customersession to be cleared when caching is active on a page but I need the customer id to show customer specific prices (B2B).
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if(!$customerSession->isLoggedIn()) {
$customerId = $customerSession->getCustomer()->getId();
}
I need to be able to get the customer id on all pages where prices are displayed for products. So, for example, the category list/grid page and the product details page.
I have read countless of bug reports on github but they all get closed by Magento as if it's no issue.
Best Answer
I have updated my response. In my previous answer, I had a block cacheable=false. This is incorrect because it do the page is not cacheable.
For knowing if the customer is logged or not, you must do the next:
When you do
$customerSession->isLoggedIn()
, it will return the correct value.To retrieve the id of the customer, the best way is how says @SohelRana in its comment, using ajax or private cache. https://devdocs.magento.com/guides/v2.2/extension-dev-guide/cache/page-caching/private-content.html