【发布时间】:2021-04-06 08:45:46
【问题描述】:
我正在尝试使用每个问题和答案的类名动态设置常见问题解答页面上所有问题和答案的架构数据。我无法使用脚本,因为它被 Yoast 的 SEO 覆盖。
到目前为止,我已经创建了下面的代码,但它没有将问题和答案引入 Google 的结构化数据工具,而且我无法循环每个问题和答案。
HTML
<div class="x-acc-item">
<span class="question">Can I order for pick up or delivery?
</span>
<div class="answer">
<p>Yes, you can!</p>
</div>
</div>
<div class="x-acc-item">
<span class="question">Do you have a rewards program?</span>
<div class="answer">
<p>We sure do!</p>
</div>
</div>
PHP
add_filter( 'wpseo_schema_webpage', 'change_faq_schema' );
function change_faq_schema( $data ) {
if ( ! is_page( 'frequently-asked-questions' ) ) {
return $data;
}
$schema = array(
'mainEntity' => array()
);
$resultquestion = array();
$resultanswer = array();
$question = "question";
$answer = "answer";
$domdocument = new DOMDocument();
$domdocument->loadHTML($doc);
$a = new DOMXPath($domdocument);
$spans = $a->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $question ')]");
$spans2 = $a->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $answer ')]");
for ($i = $spans->length - 1; $i > -1; $i--) {
$resultquestion[] = $spans->item($i)->firstChild->nodeValue;
}
for ($i = $spans2->length - 1; $i > -1; $i--) {
$resultanswer[] = $spans2->item($i)->firstChild->nodeValue;
}
$data['mainEntity'] = array(
'@type' => "Question",
'name' => $resultquestion,
"acceptedAnswer" => array(
"@type" => "Answer",
"text" => $resultanswer
)
);
return $data;
}
【问题讨论】: