ModifyHrefLangTagsEvent

The PSR-14 event \TYPO3\CMS\Frontend\Event\ModifyHrefLangTagsEvent is available to alter the hreflang tags just before they get rendered.

The class \TYPO3\CMS\Seo\HrefLang\HrefLangGenerator (identifier typo3-seo/hreflangGenerator) is also available as an event. Its purpose is to provide the default hreflang tags. This way it is possible to register a custom event listener after or instead of this implementation.

Example

With after and before, you can make sure your own listener is executed after or before the given identifiers.

EXT:my_extension/Classes/Frontend/EventListener/MyEventListener.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Frontend\EventListener;

use TYPO3\CMS\Core\Attribute\AsEventListener;
use TYPO3\CMS\Frontend\Event\ModifyHrefLangTagsEvent;

#[AsEventListener(
    identifier: 'my-extension/cache-timeout',
    after: 'typo3-seo/hreflangGenerator',
)]
final class MyEventListener
{
    public function __invoke(ModifyHrefLangTagsEvent $event): void
    {
        $hrefLangs = $event->getHrefLangs();
        $request = $event->getRequest();

        // Do anything you want with $hrefLangs
        $hrefLangs = [
            'en-US' => 'https://example.org',
            'nl-NL' => 'https://example.org/nl',
        ];

        // Override all hrefLang tags
        $event->setHrefLangs($hrefLangs);

        // Or add a single hrefLang tag
        $event->addHrefLang('de-DE', 'https://example.org/de');
    }
}

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.

API

class TYPO3\CMS\Frontend\Event\ModifyHrefLangTagsEvent

Listeners to this event will be able to modify the hreflang tags that will be generated. You can use this when you have an edge case language scenario and need to alter the default hreflang tags.

getHrefLangs()
Return type

array

getRequest()
Return type

Psr\Http\Message\ServerRequestInterface

setHrefLangs(array $hrefLangs)

Set the hreflangs. This should be an array in format:

[
    'en-US' => 'https://example.com',
    'nl-NL' => 'https://example.com/nl'
]
Parameters
  • $hrefLangs (array) -- the hrefLangs

addHrefLang(string $languageCode, string $url)

Add a hreflang tag to the current list of hreflang tags

Parameters
  • $languageCode (string) -- The language of the hreflang tag you would like to add. For example: nl-NL

  • $url (string) -- The URL of the translation. For example: https://example.com/nl