ModifyUrlForCanonicalTagEvent¶
With the PSR-14 event \TYPO3\
the URL for the href
attribute of the canonical tag can be altered or
emptied.
New in version 12.4.9
The methods get
and get
have been added.
Changed in version 13.0
The event is being dispatched after the standard functionality has been
executed, such as fetching the URL from the page properties. Effectively,
this also means that get
might already return a non-empty
string.
Note
Changed in version 13.0
The event is even dispatched in case the canonical tag generation is
disabled via TypoScript
(disableCanonical) or via
the page property no_
. If disabled, the
\TYPO3\
is
thrown. The exception is caught and transferred to the event, allowing
listeners to determine whether the generation is disabled, using the
get
method, which either
returns the exception with the corresponding reason or null
.
Example¶
Changing the host of the current request and setting it as canonical:
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\Seo\EventListener;
use TYPO3\CMS\Core\Attribute\AsEventListener;
use TYPO3\CMS\Seo\Event\ModifyUrlForCanonicalTagEvent;
use TYPO3\CMS\Seo\Exception\CanonicalGenerationDisabledException;
#[AsEventListener(
identifier: 'my-extension/modify-url-for-canonical-tag',
)]
final readonly class MyEventListener
{
public function __invoke(ModifyUrlForCanonicalTagEvent $event): void
{
if ($event->getCanonicalGenerationDisabledException() instanceof CanonicalGenerationDisabledException) {
return;
}
// Only set the canonical in our example when the tag is not disabled
// via TypoScript or via "no_index" in the page properties.
$currentUrl = $event->getRequest()->getUri();
$newCanonical = $currentUrl->withHost('example.com');
$event->setUrl((string)$newCanonical);
}
}
New in version 13.0
The PHP attribute \TYPO3\
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/
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 ModifyUrlForCanonicalTagEvent ¶
-
- Fully qualified name
-
\TYPO3\
CMS\ Seo\ Event\ Modify Url For Canonical Tag Event
PSR-14 event to alter (or empty) a canonical URL for the href="" attribute of a canonical URL.
- getUrl ( ) ¶
-
- Returns
-
string
- setUrl ( string $url) ¶
-
- param $url
-
the url
- getRequest ( ) ¶
-
- Returns
-
\Psr\
Http\ Message\ Server Request Interface
- getPage ( ) ¶
-
- Returns
-
\TYPO3\
CMS\ Core\ Domain\ Page
- getCanonicalGenerationDisabledException ( ) ¶
-
- Returns
-
?\
TYPO3\ CMS\ Seo\ Exception\ Canonical Generation Disabled Exception