Richsnippets.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. /**
  3. * Copyright © 2016 Ihor Vansach (ihor@magefan.com). All rights reserved.
  4. * See LICENSE.txt for license details (http://opensource.org/licenses/osl-3.0.php).
  5. *
  6. * Glory to Ukraine! Glory to the heroes!
  7. */
  8. namespace Magefan\Blog\Block\Post\View;
  9. use Magento\Store\Model\ScopeInterface;
  10. /**
  11. * Blog post view rich snippets
  12. */
  13. class Richsnippets extends Opengraph
  14. {
  15. /**
  16. * @param array
  17. */
  18. protected $_options;
  19. /**
  20. * Retrieve snipet params
  21. *
  22. * @return array
  23. */
  24. public function getOptions()
  25. {
  26. if ($this->_options === null) {
  27. $post = $this->getPost();
  28. $logoBlock = $this->getLayout()->getBlock('logo');
  29. if (!$logoBlock) {
  30. $logoBlock = $this->getLayout()->getBlock('amp.logo');
  31. }
  32. $this->_options = [
  33. '@context' => 'http://schema.org',
  34. '@type' => 'BlogPosting',
  35. '@id' => $post->getPostUrl(),
  36. 'author' => $this->getAuthor(),
  37. 'headline' => $this->getTitle(),
  38. 'description' => $this->getDescription(),
  39. 'datePublished' => $post->getPublishDate('c'),
  40. 'dateModified' => $post->getUpdateDate('c'),
  41. 'image' => [
  42. '@type' => 'ImageObject',
  43. 'url' => $this->getImage() ?:
  44. ($logoBlock ? $logoBlock->getLogoSrc() : ''),
  45. 'width' => 720,
  46. 'height' => 720,
  47. ],
  48. 'publisher' => [
  49. '@type' => 'Organization',
  50. 'name' => $this->getPublisher(),
  51. 'logo' => [
  52. '@type' => 'ImageObject',
  53. 'url' => $logoBlock ? $logoBlock->getLogoSrc() : '',
  54. ],
  55. ],
  56. 'mainEntityOfPage' => $this->_url->getBaseUrl(),
  57. ];
  58. }
  59. return $this->_options;
  60. }
  61. /**
  62. * Retrieve author name
  63. *
  64. * @return array
  65. */
  66. public function getAuthor()
  67. {
  68. if ($author = $this->getPost()->getAuthor()) {
  69. if ($author->getTitle()) {
  70. return $author->getTitle();
  71. }
  72. }
  73. // if no author name return name of publisher
  74. return $this->getPublisher();
  75. }
  76. /**
  77. * Retrieve publisher name
  78. *
  79. * @return array
  80. */
  81. public function getPublisher()
  82. {
  83. $publisher = $this->_scopeConfig->getValue(
  84. 'general/store_information/name',
  85. ScopeInterface::SCOPE_STORE
  86. );
  87. if (!$publisher) {
  88. $publisher = 'Magento2 Store';
  89. }
  90. return $publisher;
  91. }
  92. /**
  93. * Render html output
  94. *
  95. * @return string
  96. */
  97. protected function _toHtml()
  98. {
  99. return '<script type="application/ld+json">'
  100. . json_encode($this->getOptions())
  101. . '</script>';
  102. }
  103. }