How to get current customer group id in magento2
Magento\Customer\Model\Session $customerSession
using this class you will get current customer group id
protected $_customerSession;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
) {
$this->_customerSession = $customerSession;
}
public function getGroupId(){
if($this->_customerSession->isLoggedIn()):
echo $customerGroup=$this->_customerSession->getCustomer()->getGroupId();
endif;
}
NOTE: You only get customer id if customer logged in
you can get group Id by following code
protected $_customerSession;
public function __construct(
....
\Magento\Customer\Model\Session $customerSession,
....
) {
$this->_customerSession = $customerSession;
}
public function getGroupId(){
if($this->_customerSession->isLoggedIn()):
echo $customerGroup=$this->_customerSession->getCustomer()->getGroupId();
endif;
}
By default, Magento will clear the customer session: \Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml
.
https://magento.stackexchange.com/a/92133/33057
Take a look:
vendor/magento/module-customer/Model/Context.php
/**
* Customer group cache context
*/
const CONTEXT_GROUP = 'customer_group';
/**
* Customer authorization cache context
*/
const CONTEXT_AUTH = 'customer_logged_in';
We can check the logged in customer and customer group:
/**
* @var \Magento\Framework\App\Http\Context $httpContext
*/
$isLogged = $this->httpContext->getValue(Context::CONTEXT_AUTH);
$customerGroupId = $this->httpContext->getValue(Context::CONTEXT_GROUP);
Put these code lines in your block.
There is another good explanation here:
https://sohel.dev/how-to-get-customer-id-from-block-when-full-page-cache-enable-in-magento-2/