class-schema-faq-questions.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Frontend\Schema
  6. */
  7. /**
  8. * Returns a question object for each question in an FAQ block.
  9. *
  10. * @since 11.1
  11. *
  12. * @property array $data The Schema array.
  13. * @property WP_Block_Parser_Block $block The block we're taking the questions out of.
  14. * @property WPSEO_Schema_Context $context A value object with context variables.
  15. * @property int $position The position in the list.
  16. */
  17. class WPSEO_Schema_FAQ_Questions {
  18. /**
  19. * The Schema array.
  20. *
  21. * @var array
  22. */
  23. private $data;
  24. /**
  25. * All the blocks of this block-type.
  26. *
  27. * @var WP_Block_Parser_Block
  28. */
  29. private $block;
  30. /**
  31. * Position in the list.
  32. *
  33. * @var int
  34. */
  35. private $position;
  36. /**
  37. * WPSEO_Schema_FAQ_Questions constructor.
  38. *
  39. * @param array $data Our schema graph.
  40. * @param WP_Block_Parser_Block $block The FAQ block of this type.
  41. * @param WPSEO_Schema_Context $context A value object with context variables.
  42. */
  43. public function __construct( $data, $block, $context ) {
  44. $this->data = $data;
  45. $this->block = $block;
  46. $this->context = $context;
  47. $this->position = 0;
  48. }
  49. /**
  50. * Find an image based on its URL and generate a Schema object for it.
  51. *
  52. * @return array The Schema with Questions added.
  53. */
  54. public function generate() {
  55. foreach ( $this->block['attrs']['questions'] as $question ) {
  56. if ( ! isset( $question['jsonAnswer'] ) || empty( $question['jsonAnswer'] ) ) {
  57. continue;
  58. }
  59. $this->data[] = $this->generate_question_block( $question );
  60. }
  61. return $this->data;
  62. }
  63. /**
  64. * Generate a Question piece.
  65. *
  66. * @param array $question The question to generate schema for.
  67. *
  68. * @return array Schema.org Question piece.
  69. */
  70. protected function generate_question_block( $question ) {
  71. $url = $this->context->canonical . '#' . esc_attr( $question['id'] );
  72. return [
  73. '@type' => 'Question',
  74. '@id' => $url,
  75. 'position' => $this->position ++,
  76. 'url' => $url,
  77. 'name' => wp_strip_all_tags( $question['jsonQuestion'] ),
  78. 'answerCount' => 1,
  79. 'acceptedAnswer' => [
  80. '@type' => 'Answer',
  81. 'text' => strip_tags( $question['jsonAnswer'], '<h1><h2><h3><h4><h5><h6><br><ol><ul><li><a><p><b><strong><i><em>' ),
  82. ],
  83. ];
  84. }
  85. }