Product detail page: Current category from Registry sometimes incorrect
-
03-10-2020 - |
Question
For different customer journeys, I would like to differentiate between a product being displayed in a category (via host/category/category/product.html
) and the product being displayed without a category path (host/product.html
). The former is how a product is displayed when the customer navigates through the tree and finds a product, the latter when a product is displayed via the search function or the customer lands on the product itself via outside search engines.
Now, the code I use to differentiate is like this:
$currentCategory = Mage::registry('current_category');
if($currentCategory) {
$paths = array_splice(explode('/', $currentCategory->getPath()), 2);
if(count($paths)>1) {
...
However, I have discovered a problem with that differentiation. If I navigate to a product using the tree (host/category/category/product.html
), then immediately afterwards opening up the same product using the search function (host/product.html
), the code
$currentCategory = Mage::registry('current_category');
still returns the category as if the product is currently being displayed via the category subtree (host/category/category/product.html
). Opening the same URL in a new browser window fixes the "problem". Opening another category list page without opening another product detail page, then going back to the original product fixes that as well.
I would conclude that this means that getting the current category from the registry is not a sufficient way to determine if this product detail page is called under a subcategory or not. Is there a way/function that allows to make that distinction, short or grabbing the current URL and manually parsing the path?
Solution
You get wrong results because magento caches registry.
I see two options here
Uncache your block if it is independent and included via xml with
<reference name="needed block"> <action method="setCacheLifetime"></action> </reference>
getRequest()->getParams() to grab your category via URL.
This is what magento do if registry category id is not set.
Since I'm on mobile I can't show you more code, my hint is to look what registry current category does to provide you the ID.