Magento – How to Override Mage_Catalog_Block_Product_View with a Custom Module

magento-1.9magento-coreoverrides

I am trying to override Mage_Catalog_Block_Product_View through a custom module in order to strip html tags out of the default meta description. I'm not sure what I'm missing or if I'm making any mistakes.

app/code/local/Companyname/Catalog/Block/Product/View.php

class Companyname_Catalog_Block_Product_View extends Mage_Catalog_Block_Product_View 
{
/**
 * Add meta information from product to head block
 *
 * @return Mage_Catalog_Block_Product_View
 */
protected function _prepareLayout()
{
    parent::_prepareLayout();
    $this->getLayout()->createBlock('catalog/breadcrumbs');
    $headBlock = $this->getLayout()->getBlock('head');
    if ($headBlock) {
        $product = $this->getProduct();
        $title = $product->getMetaTitle();
        if ($title) {
            $headBlock->setTitle($title);
        }
        $keyword = $product->getMetaKeyword();
        $currentCategory = Mage::registry('current_category');
        if ($keyword) {
            $headBlock->setKeywords($keyword);
        } elseif ($currentCategory) {
            $headBlock->setKeywords($product->getName());
        }
        $description = $product->getMetaDescription();
        if ($description) {
            $headBlock->setDescription( ($description) );
        } else {
            /* Added $strippeddesc to remove html tags from default description if used in meta description */
            $strippeddesc = html_entity_decode(strip_tags($product->getDescription()));
            $headBlock->setDescription(Mage::helper('core/string')->substr($strippeddesc, 0, 255));
        }
        if ($this->helper('catalog/product')->canUseCanonicalTag()) {
            $params = array('_ignore_category' => true);
            $headBlock->addLinkRel('canonical', $product->getUrlModel()->getUrl($product, $params));
        }
    }
    return parent::_prepareLayout();
}
}

app/code/local/Companyname/Catalog/etc/config.xml

<config>
  <modules>
    <Companyname_Catalog>
      <version>0.1.0</version>
    </Companyname_Catalog>
    <depend>
      <Mage_Catalog/>
    </depend>
  </modules>
  <global>
    <blocks>
      <catalog>
        <rewrite>
          <product_view>Companyname_Catalog_Block_Product_View</product_view>
        </rewrite>
      </catalog>
    </blocks>
  </global>
</config>

Best Answer

Can't you just strip the html in the head.phtml template instead of overriding a class method?

Off the top of my head you probably should look at Mage_Page_ Block_Head if you want to override that method

Related Topic