Search code examples
joomlajoomla2.5canonical-link

Modify the existing canonical link in header


I am using Joomla 2.5 and I want to change the canonical link in the header. I do this in category view (components/com_content/category/tmpl/default.php)

$url        = JURI::root();
$sch        = parse_url($url, PHP_URL_SCHEME);
$server     = parse_url($url, PHP_URL_HOST);
$canonical  = $this->escape($_SERVER['REQUEST_URI']);    
$document->addCustomTag('<link rel="canonical" href="'.$sch.'://'.$server.$canonical.'"/>');

It prints the right canonical, but it also leaves the old canonical link there so that I have 2 canonical links in the header.

How can I change or delete the old canonical link?


Solution

  • What you probably want to do instead is something like the following:

    $doc_data = $document->getHeadData();
    $url        = JURI::root();
    $sch        = parse_url($url, PHP_URL_SCHEME);
    $server     = parse_url($url, PHP_URL_HOST);
    $canonical  = $this->escape($_SERVER['REQUEST_URI']); 
    $newtag     = '<link rel="canonical" href="'.$sch.'://'.$server.$canonical.'"/>'
    
    $replaced = false;
    foreach ($doc_data['custom'] as $key=>$c) {
        if (strpos($c, 'rel="canonical"')!==FALSE) {
            $doc_data['custom'][$key] = $newtag;
            $replaced = true;
        }
    }
    if (!$replaced) {
        $doc_data['custom'][] = $newtag;
    }
    
    $document->setHeadData($doc_data);
    

    This will grab all of the current head data from the document, including the canonical link that you want to replace. It will search through the custom set (where I'm guessing this will be) and if it finds it, replace it with yours. If it doesn't find it, then it tacks it on at the end. Just in case.

    Potential problems with this that I can see right away:

    1. If the tag contained rel='canonical' with single quotes it would not be found, so you may have to adjust that.
    2. The tag may have been placed in a different section of what I've termed $doc_data. You may want to do a var_dump($doc_data}; to confirm the location of the variable in this array.