1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
<?php
namespace Yoast\WP\SEO\Generators\Schema;
/** * Returns schema FAQ data. */ class FAQ extends Abstract_Schema_Piece {
/** * Determines whether or not a piece should be added to the graph. * * @return bool */ public function is_needed() { if ( empty( $this->context->blocks['yoast/faq-block'] ) ) { return false; }
if ( ! \is_array( $this->context->schema_page_type ) ) { $this->context->schema_page_type = [ $this->context->schema_page_type ]; } $this->context->schema_page_type[] = 'FAQPage'; $this->context->main_entity_of_page = $this->generate_ids();
return true; }
/** * Generate the IDs so we can link to them in the main entity. * * @return array */ private function generate_ids() { foreach ( $this->context->blocks['yoast/faq-block'] as $block ) { foreach ( $block['attrs']['questions'] as $index => $question ) { if ( ! isset( $question['jsonAnswer'] ) || empty( $question['jsonAnswer'] ) ) { continue; } $ids[] = [ '@id' => $this->context->canonical . '#' . \esc_attr( $question['id'] ) ]; } }
return $ids; }
/** * Render a list of questions, referencing them by ID. * * @return array $data Our Schema graph. */ public function generate() { $graph = [];
foreach ( $this->context->blocks['yoast/faq-block'] as $block ) { foreach ( $block['attrs']['questions'] as $index => $question ) { if ( ! isset( $question['jsonAnswer'] ) || empty( $question['jsonAnswer'] ) ) { continue; } $graph[] = $this->generate_question_block( $question, ( $index + 1 ) ); } }
return $graph; }
/** * Generate a Question piece. * * @param array $question The question to generate schema for. * @param int $position The position of the question. * * @return array Schema.org Question piece. */ protected function generate_question_block( $question, $position ) { $url = $this->context->canonical . '#' . \esc_attr( $question['id'] );
$data = [ '@type' => 'Question', '@id' => $url, 'position' => $position, 'url' => $url, 'name' => $this->helpers->schema->html->smart_strip_tags( $question['jsonQuestion'] ), 'answerCount' => 1, 'acceptedAnswer' => $this->add_accepted_answer_property( $question ), ];
$data = $this->helpers->schema->language->add_piece_language( $data );
return $data; }
/** * Adds the Questions `acceptedAnswer` property. * * @param array $question The question to add the acceptedAnswer to. * * @return array Schema.org Question piece. */ protected function add_accepted_answer_property( $question ) { $data = [ '@type' => 'Answer', 'text' => $this->helpers->schema->html->sanitize( $question['jsonAnswer'] ), ];
$data = $this->helpers->schema->language->add_piece_language( $data );
return $data; } }
|