Created
October 10, 2019 14:58
-
-
Save bjo3rnf/d38795f48c04f71744af7781c390fc1f to your computer and use it in GitHub Desktop.
Custom TYPO3 metatag manager to provide fallback og:image by sliding up the rootline
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace My\Extension\MetaTag; | |
use TYPO3\CMS\Core\Resource\FileRepository; | |
use TYPO3\CMS\Core\Utility\GeneralUtility; | |
use TYPO3\CMS\Core\Utility\RootlineUtility; | |
use TYPO3\CMS\Extbase\Service\ImageService; | |
class OpenGraphMetaTagManager extends \TYPO3\CMS\Seo\MetaTag\OpenGraphMetaTagManager | |
{ | |
public function renderAllProperties(): string | |
{ | |
if (array_key_exists('og:image', $this->properties)) { | |
return parent::renderAllProperties(); | |
} | |
/** @var FileRepository $fileRepository */ | |
$fileRepository = GeneralUtility::makeInstance(FileRepository::class); | |
$pageUid = $this->getPageWithImage(); | |
if (null === $pageUid) { | |
return parent::renderAllProperties(); | |
} | |
$images = $fileRepository->findByRelation('pages', 'og_image', $pageUid); | |
/** @var ImageService $imageService */ | |
$imageService = GeneralUtility::makeInstance(ImageService::class); | |
foreach ($images as $image) { | |
$processedImage = $imageService->applyProcessingInstructions( | |
$image, | |
[ | |
'width' => '1200', // Hardcoded width, I know, too lazy | |
] | |
); | |
$this->addProperty( | |
'og:image', | |
$imageService->getImageUri($processedImage, true), | |
[ | |
'url' => $imageService->getImageUri($processedImage, true), | |
'width' => $processedImage->getProperty('width'), | |
'height' => $processedImage->getProperty('height'), | |
'type' => $processedImage->getMimeType(), | |
] | |
); | |
} | |
return parent::renderAllProperties(); | |
} | |
/** | |
* @return null|int | |
*/ | |
protected function getPageWithImage() | |
{ | |
$rootLineUtility = new RootlineUtility($GLOBALS['TSFE']->id); | |
$rootLine = $rootLineUtility->get(); | |
foreach ($rootLine as $page) { | |
if ($page['og_image'] > 0) { | |
return $page['uid']; | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment