1

I want to check the page number which appears in a URL in a phtml file. For example, if the URL is:

http://localhost/magento/index.php/shop.html?p=4

How can I get the value 4 in the .phtml file?

I am using code:

<?php $this->getRequest()->getParam('p')?> 

But it does not work in the phtml file. I am using Magento 2.3.2.

  • Good to see that you have resolved your issue. +1 for answer acceptance :) – Shoaib Munir Jan 30 at 6:07
3

you can use $this->getRequest()->getParam('p') to get page number.

Either you are in .phtml or in controller this will work

If it is not working for you then you can try this:

protected $request;
public function __construct(
    \Magento\Framework\App\Request\Http $request,
    ....//rest of parameters here
) {
   $this->request = $request;
   ...//rest of constructor here
}
public function getIddata()
{
// use 
$this->request->getParams(); // all params
    return $this->request->getParam('id');
}

Edit:

I have used this type of code $this->getRequest()->getParam('p') in .phtml before and it worked perfectly for me

| improve this answer | |
  • 1
    just clarifying here: the code snippet above must be put into a class. e.g. ViewModel or Block – Vasilii Burlacu Jan 30 at 7:56
  • $this->getRequest() should $block->getRequest(). $this usage in .phtml files has been deprecated with Magento 2. As mentioned in another comment, ViewModel is an even better idea. – bassplayer7 Jan 30 at 13:52

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.