Recover Current Product on Your Page - Magento 2

The following code shows how to create a simple class that returns the current product:

<? Php
namespace MyCompany \ MyModule \ Helper;
class MyModel extends Magento \ Framework \ App \ Helper \ AbstractHelper
{
protected $ registry;

public function __construct (
.
\ Magento \ Framework \ Registry $ registry
){
.
$ this-> registry = $ registry;
}

public function getCurrentProduct ()
{
return $ this-> registry-> registry ('current_product');
}

.
}

De \ Magento \ Framework \ Registry you can get useful information like the current product. For this you need to inject this class and show the registration method with the string "current_product" as param. getCurrentProduct () returns a product model if this was called a frontend. You need to change the identifiers for your MyCompany, MyModule, and MyModel module for your needs.

This is useful for blocks and controllers or auxiliaries that are used in frontend models.

You need to check if it is an object, because this obviously does not work as expected if you call this from adminhtml or command line. From a product model, you get additional information such as:

$ id = $ product-> getId ();
$ name = $ product-> getName ();

You may need the current visited product to enable some product-dependent frontend Skin / Design customization or additional product features. This is also useful if you want to track your user and get details of the products you have visited. This solution is recommended!

You can find another using the object manager. Please note that using the object manager on frontend sites is a bad practice as this disrupts the performance of your store. Injecting objects is highly recommended and always the best solution.

Conclusion

It's easy to get additional information for each front-end site, such as current category or current product.

Rate This Article!

Click on the stars to give a note of 1 to 5.

1 star2 stars3 stars4 stars5 stars (No Ratings Yet)
Loading ...

Doubts? Make a comment below or send us a message by clicking here.

Your email address will not be published. Required fields are marked with *