ModifyUrlForCanonicalTagEvent¶
With the PSR-14 event \TYPO3\CMS\Seo\Event\ModifyUrlForCanonicalTagEvent
the URL for the href
attribute of the canonical tag can be altered or
emptied.
Example¶
Changing the host of the current request and setting it as canonical:
EXT:my_extension/Classes/Seo/EventListener/MyEventListener.php¶
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\Seo\EventListener;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Attribute\AsEventListener;
use TYPO3\CMS\Seo\Event\ModifyUrlForCanonicalTagEvent;
#[AsEventListener(
identifier: 'my-extension/modify-url-for-canonical-tag'
)]
final class MyEventListener
{
public function __invoke(ModifyUrlForCanonicalTagEvent $event): void
{
// Note: $event->getUrl() is dispatched with the empty string value ''
$currentUrl = $this->getRequest()->getUri();
$newCanonical = $currentUrl->withHost('example.com');
$event->setUrl((string)$newCanonical);
}
private function getRequest(): ServerRequestInterface
{
return $GLOBALS['TYPO3_REQUEST'];
}
}
New in version 13.0: The PHP attribute \TYPO3\CMS\Core\Attribute\AsEventListener
has been
introduced to tag a PHP class as an event listener. Alternatively, or if you
need to be compatible with older TYPO3 versions, you can also register an
event listener via the Configuration/Services.yaml
file. Switch to
an older version of this page for an example or have a look at the section
Implementing an event listener in your extension.