Search code examples
magentoseocanonical-link

Magento : how to set canonical URL for product?


I'm using megento 1.7.0.2, some products have 3 or 4 different urls :

example.com/category1/product1.html
example.com/category1/category2/product1.html
example.com/prodcut1.html
...

In the HTML code of Prodcut1, magento is adding this tag :

<link rel="canonical" href="http://example.com/product1.html">

How can choose another URL ? e.g :

<link rel="canonical" href="http://example.com/category1/category2/product1.html">

Solution

  • Unfortunately it can't be done with the default Magento functionality.

    First, you need to decide which criteria to take into account when defining the canonical URL.

    Our Magento SEO extension will let you choose:

    1. The longest URLs (the ones that contain the biggest # of characters)
    2. URLs with the maximum category depth level
    3. Non-root URLs with the minimum category depth level (and at least Non-root URLs with the
    4. Non-rootURLs with the minimum # of characters (and at least one category)

    These URLs can also be added to an HTML and XML sitemaps.

    On top of that, you can individually select any URL for any chosen product or enter a custom canonical.

    You can also try it on your own, using the collection of re-writes. For the community edition it looks like this:

    $collection = Mage::getResourceModel('core/url_rewrite_collection');
            $collection->getSelect()->where('product_id = ? AND category_id is not null AND is_system = 1', $productId,  Zend_Db::INT_TYPE); <- с наличием категории
            $collection->addStoreFilter(Mage::app()->getStore()->getId());
            $collection->getSelect()->order(new Zend_Db_Expr('LENGTH(request_path) ' . 'DESC')); <- sorting that depends on the principle of canonical settings.
            $rewriteModel = $collection->getFirstItem(); 
            var_dump($rewriteModel); <-damp of the acquired object
    

    Then you need to connect base store URL + "request_path" property form object + URL suffix (if needed).