Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento - get current product

I have a sidebar block in my layout that is being displayed on different pages.

In this block I have a list of products, and I want to select the current product when I'm on a product page.

I'm using :

$current_product = Mage::registry('current_product');

to get the current product, but this works only for the first time I'm loading the product page. When I select a different product the code above returns the same value (the first product).

I'm assuming this happens because I'm using Magento cache. What can I do to get the right value?

The same thing happens when I use:

$currentCategory = Mage::registry('current_category');

The sidebar block is a navigation template I've added here: ..\app\design\frontend\default\mytheme\template\catalog\navigation\page_left.phtml.

I'm adding it to the layout with this XML :

<block type="catalog/navigation" name="left.navigation.block" as="left.navigation.block" template="catalog/navigation/page_left.phtml"/>
like image 239
Shani1351 Avatar asked Jul 16 '12 14:07

Shani1351


People also ask

How can I get current store ID in Magento 2?

You can get store ID by calling the block function in your phtml file. echo $block->getStoreId(); Using Object Manager.

How do I get all categories in Magento 2?

You can achieve functionality using the Catalog module interface Magento\Catalog\Api\CategoryListInterface with getList() method to get a category list.


3 Answers

How to get current product id

Try below code to get currently loaded product id:

$product_id = $this->getProduct()->getId();

When you don’t have access to $this, you can use Magento registry:

$product_id = Mage::registry('current_product')->getId();
like image 143
drsndodiya Avatar answered Nov 09 '22 04:11

drsndodiya


If you're not willing to use your own block class inheriting from Mage_Catalog_Block_Navigation, in which you could set your own cache informations (to make it eg depending on the current product), you can get rid of the cache for your block by using this in its layout definition :

<block type="catalog/navigation" name="left.navigation.block" as="left.navigation.block" template="catalog/navigation/page_left.phtml">
    <action method="unsetData"><key>cache_lifetime</key></action>
</block>
like image 28
blmage Avatar answered Nov 09 '22 05:11

blmage


$_proId  = $this->getProduct()->getId();
$_product= Mage::getModel('catalog/product')->load($_proId);

This actually does work. It has been down voted above, however it worked for me. I understand that the product does indeed load when you use getProduct(), however, I was only getting partial information of the product. Getting the ID and reloading the product brought back all the information.

It might be specific to a version of Magento, however it does work though it looks stupid.

like image 2
Adrian Avatar answered Nov 09 '22 04:11

Adrian