I have created an EAV entity (that represents the brand) which can be associated to a product as an attribute. Now, I would like to add the name of the brand to the product view URL. I would like something like this:
http://myhost.com/category-name/brand-name/product-name
Is there a way to extend the url rewrite for products view?
1 Answer 1
In order to create url key with "/" sign you need to override Mage_Catalog_Model_Product_Url's formatUrlKey() method.
You can do it like so:
class Vendor_Module_Model_Catalog_Product_Url extends Mage_Catalog_Model_Product_Url
{
/**
* Format Key for URL
*
* @param string $str
* @return string
*/
public function formatUrlKey($str)
{
// added '/' character
$urlKey = preg_replace('#[^0-9a-z\/.]+#i', '-', Mage::helper('catalog/product_url')->format($str));
$urlKey = strtolower($urlKey);
$urlKey = trim($urlKey, '-');
return $urlKey;
}
}
You can override beforeSave() method of the Backend Model of Catalog Product Urlkey attribute as following:
class Vendor_Module_Model_Catalog_Product_Attribute_Backend_Urlkey
extends Mage_Catalog_Model_Product_Attribute_Backend_Urlkey
{
/**
* Before save
*
* @param Varien_Object $object
* @return Mage_Catalog_Model_Resource_Product_Attribute_Backend_Urlkey
* @overridden
*/
public function beforeSave($object)
{
$attributeName = $this->getAttribute()->getName();
$urlKey = $object->getData($attributeName);
if ($urlKey == '') {
$urlKey = "{$object->getBrandName()}/{$object->getName()}";
}
$object->setData($attributeName, $object->formatUrlKey($urlKey));
return $this;
}
}
Now while product is being saved, if url key empty it will automatically create an 'brand-name/name' like url. If it comes to category name it is a matter of magento configuration to or not to add category name at the begining of URL address.
Alternatively check out this free extension, it does exactly what you require: https://www.magentocommerce.com/magento-connect/custom-product-urls-seo.html
Explore related questions
See similar questions with these tags.