PHP Joomla! 6 Joomla! 5 Joomla! 3 (Legacy) Template Override Basic

Set Canonical Link, Open Graph and Twitter Cards Dynamically

Outputs rel="canonical", og:title, og:description, og:image and twitter:card cleanly through HtmlDocument for optimal SEO and sharing.

Updated on 24 November 2026 60 copies 202 views
components/com_example/src/View/Item/HtmlView.php
<?php

declare(strict_types=1);

use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;

$doc       = Factory::getApplication()->getDocument();
$canonical = Uri::getInstance()->toString(['scheme', 'host', 'port', 'path']);
$ogImage   = Uri::root() . 'images/pontomega-og.jpg';

$doc->addHeadLink($canonical, 'canonical');
$doc->setMetaData('og:type', 'article', 'property');
$doc->setMetaData('og:url', $canonical, 'property');
$doc->setMetaData('og:title', (string) $this->item->title, 'property');
$doc->setMetaData('og:description', (string) $this->item->metadesc, 'property');
$doc->setMetaData('og:image', $ogImage, 'property');
$doc->setMetaData('twitter:card', 'summary_large_image');
Pass "property" as the third argument for Open Graph tags and default "name" for Twitter Cards.
components/com_example/src/View/Item/HtmlView.php
<?php
$doc = JFactory::getDocument();
$doc->addHeadLink(JURI::current(), 'canonical');
$doc->setMetaData('og:title', $this->item->title, 'property');
$doc->setMetaData('og:image', JURI::root() . 'images/og.jpg', 'property');
Legacy Joomla 3 equivalent via JFactory::getDocument().

Technical explanation and best practices

In custom components or landing page overrides, set an absolute canonical link and Open Graph metadata with $doc->setMetaData($key, $val, 'property') so links preview accurately on social networks.

Direct Engineering

Have a Joomla project or technical challenge in mind?

From architectural diagnosis to production deployment, directly with the engineer.