Skip to content

Instantly share code, notes, and snippets.

@bjo3rnf
Created October 10, 2019 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjo3rnf/d38795f48c04f71744af7781c390fc1f to your computer and use it in GitHub Desktop.
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
<?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