I ask this question fully aware that the answer I'm seeking is pretty obvious and probably right in front of me. Unfortunately, I cannot see it so I need some help. And yes, I have seen this already: https://stackoverflow.com/a/11708444/731596 and while it applies to my issue it doesn't demonstrate how to accomplish my goal.

Here's the situation: I am modifying meta tags on the product details page. I have copied over Product/View.php into app/code/local/ and so far, I've been able to customize the page title and some of the keyword content to my needs.

For the keywords, my goal is to have it contain the following information:

Product Title, Category3, Category2, Category1, SKU, Company Name

I have been successful getting Product Title, SKU and Company Name, but my problem is in listing out at least three of the categories under which a product resides. The most I am able to get is one category using the following code:

$categoryCollection = $product->getCategoryCollection();

        foreach ($categoryCollection as $category) {
            $topCategory = Mage::getModel('catalog/category')->load($category->getId());
            break;
        }
  $topCategory->getName();

I think that I am very close and believe that my problem is how to iterate through categoryCollection and then display each category contained therein. Everything I have tried has failed and the best I can do is get one category for a product displaying in the keyword meta tag.

Again, I'm sure the answer is painfully obviously so please forgive if that is the case and I would greatly appreciate any help.

有帮助吗?

解决方案

You have already got the View.php file, that's good, to make this Q/A useful to others, I will also list the folder where you can get this file from (Magento 1.7): /app/code/core/Mage/Catalog/Block/Product/View.php

You are also right about the logic there to get category, the reason you are getting only one category is because the "break", which ends execution of "foreach" right after its first run. See: http://www.php.net/manual/en/control-structures.break.php

Let's change your code a little bit:

Get all categories:

$categoryCollection = $product->getCategoryCollection();

  foreach ($categoryCollection as $category) {
        $topCategory = Mage::getModel('catalog/category')->load($category->getId());
        $keyword .= ' '.$topCategory->getName();
    }
  $headBlock->setKeywords($keyword);  

Get 3 categories:

$i = 0;
$categoryCollection = $product->getCategoryCollection();

  foreach ($categoryCollection as $category) {

        if($i++ == 3){break;}
        $topCategory = Mage::getModel('catalog/category')->load($category->getId());
        $keyword .= ' '.$topCategory->getName();
    }
  $headBlock->setKeywords($keyword);  
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top