Search code examples
phpurljoomlaseocanonical-link

Get Active Menu-URL


Because there isn't a working plugin for Joomla 2.5 which provides canonical URLs (beside SEF404), I'll try to "hack" my template and include a canonical URL when needed.

Because every menu item is accessible with different URL's and GET-Parameters, I want to include the canonical URL when needed.

I think the easiest solution is to get the URL of the active menu-item and if the accessed url differs to this, then included the canonical-tag into the header (of index.php of the template).

I've basic PHP knowledge, but I have no idea how to get the URL of the active menu item and the accessed URL. Can anybody tell me how to get this information? If I have this, then I can simply compare it and if it's different, add the tag.

Please post some sample code how to get this information.

EDIT: Here is some basic information (only related to the "homepage"), but for me this code doesn't work. http://writenowdesign.com/joomla-tutorials/joomla-trips-and-tricks/add-canonical-url-link-to-joomla-home-page/

EDIT2: For example:

<?php

// Source: http://www.php.de/php-einsteiger/91123-erledigt-aktuelle-browser-url-ausgeben-funktion-zweckdienlich-2.html
function getUrl($arrAddParam = false, $xhtmlValid = false, $anchor = false, $dropCalledArgs = false) { 

    $url  = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://'; 
    $url .= $_SERVER['SERVER_NAME']; 
    $url .= $_SERVER['SCRIPT_NAME']; 

    // merge input and user param arrays 
    $arrParam = is_array($arrAddParam) ? $arrAddParam : array(); 
    if ($dropCalledArgs === false) $arrParam = array_merge($_GET,$arrParam); 

    if (!empty($arrParam)) { 
        $arg_separator = $xhtmlValid ? '&amp;' : '&'; 
        $url .= "?". http_build_query($arrParam, '', $arg_separator); 
    } 

    // anchor 
    if ($anchor !== false) { 
        $url .= '#'.$anchor; 
    }     

    return $url; 
}

// Get the application object
$app = JFactory::getApplication();
// Get's the menu object
$menu = $app->getMenu();
// Current URL
$activeUrl = getUrl();
// SHOULD get the active menu target as string, but it's an object
// THIS is my question how to get the URL of the current active menu item
$menuUrl = $menu->getActive();

?>

EDIT 3: Here is a possibility to get this url. But I need the SEO url and not the "normal one".


Solution

  • In the meanwhile I found a solution. Maybe this helps somebody else in my situation:

    <?php
    
    // Get SEO Page URL
    $pageUrl = JURI::current();
    // Get URI Object
    $uri = & JFactory::getURI();
    // Get URI String
    $pageUri = $uri->toString();
    
    // Check if there is a difference
    if ($pageUrl != $pageUri){
        // Insert canonical tag when needed
        echo '<link rel="canonical" href="'.$pageUrl.'" />';
    }
    
    ?>