2

I want to get visitor Id in my custom block for getting product view history of non logged in customer

  public function __construct(
    \Magento\Customer\Model\Visitor $customerVisitor
   ){
     $this->_customerVisitor = $customerVisitor;
   }

    .....
    echo $visitorId = $this->_customerVisitor->getId();exit;
   ....

but i am not getting any value how to get visitor id?

  • 1
    Your code looks ok to me. Did you declare protected $_customerVisitor; in your class ? – Raphael at Digital Pianism Sep 1 '16 at 8:16
  • NO i don't, can you tell me if i am not declare protected $_customerVisitor; this than what happened? – Newbie Sep 1 '16 at 8:24
1

According to what you told me in the comments, the problem comes from the fact that you didn't declare the protected variable to store \Magento\Customer\Model\Visitor

So in your case when you call $this->_customerVisitor it doesn't work because this variable is not declared.

You need to add the following code before the __construct() method declaration to fix your issue:

protected $_customerVisitor;
  • i declare variable before __construct() but i am not getting visitor id – Newbie Sep 1 '16 at 8:28
  • @Newbie are you sure your block is getting called ? – Raphael at Digital Pianism Sep 1 '16 at 8:29
  • yes it my block is getting called – Newbie Sep 1 '16 at 8:30
  • @Newbie well I'm not sure what's wrong here in that case – Raphael at Digital Pianism Sep 1 '16 at 8:37
1

Use \Magento\Customer\Model\Visitor class to get visitor data

protected $_visitor;

public function __construct(
    ...
    \Magento\Customer\Model\Visitor $visitor
    ...
) {
    $this->_visitor = $visitor;
}

public function getVisitors()
{
    $visitors = $this->_visitor->getCollection();
    print_r($visitors); //Print visitors data
}
0

Its your Full page cache. If you disable the full page cache, you will get the visitor data. It seems kind of Magento Bug, which is related to recently view products block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.