errorous
errorous

Reputation: 1071

Magento: adding link in head to every frontend page

I have a module that needs a canonical link injected into <head> on literally every page on frontend. Is there a way to do it? Currently, given my module doesn't need its own page on frontend, nor any controllers whatsoever, I have only set the helper in my config.xml. Now, I do have an xml in layout, but the problem is that I need to change canonical link attributes based on user input(in admin), so XML doesn't fit. Yes, I could indeed fopen said fronted layout xml file, then replace what I need, then write new content back to it, but I wanted to check first whether there's other way for achieving that.

Upvotes: 0

Views: 1413

Answers (1)

Per
Per

Reputation: 96

You can hook in on the core_block_abstract_prepare_layout_before event and use the Head block's addLinkRel method to add the link tag.

In your config.xml you need to define an observer like so:

<events>
    <core_block_abstract_prepare_layout_before>
        <observers>
            <your_module>
                <class>Your_Module_Model_Observer</class>
                <method>addCanonicalLink</method>
            </your_module>
        </observers>
    </core_block_abstract_prepare_layout_before>
</events>

Create an observer class in the Model directory

<?php
class Your_Module_Model_Observer {
    public function addCanonicalLink(Varien_Event_Observer $observer) {
        $block = $observer->getData('block');
        if ($block->getNameInLayout() === 'head') {
            // this will add <link rel="canonical" href="http://your-url.com">
            $block->addLinkRel('canonical', 'http://your-url.com');

            // If you need more attributes on the link tag use addItem instead
            // This will add <link rel="canonical" href="http://your-url" attr="Your Attribute">
            // $block->addItem('link_rel',  'http://your-url', 'rel="canonical" attr="Your Attribute"')
        }
    }
}

Update:

Since the core head.phtml template files run echo $this->getChildHtml() (render all children) it is possible to insert tags by adding a core/text block as a child and add a text string to it (just like you already tried with xml). If addItem doesn't fit your needs, this is more flexible as you can insert any string this way. Replace thie $block->addLinkRel line with

$canonical = $block->getLayout()->createBlock('core/text')
    ->setText('<link rel="canonical" href="http://your-url.com">')
$block->append($canonical); 

Upvotes: 2

Related Questions