如何解决为常见问题页面动态设置架构数据
我正在尝试使用每个问题和答案的类名动态设置常见问题页面上所有问题和答案的架构数据。我无法使用脚本,因为它被 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(' ',' $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;
}
解决方法
您可以在特定页面上禁用 Yoast,然后您可以将自己的架构加入队列。
从 Yoast SEO 14.0 开始,我们改变了您与 Yoast SEO 的输出。但是,在某些情况下,您可能希望禁用 Yoast SEO 在特定帖子上的输出。
<?php
add_action( 'template_redirect','remove_wpseo' );
/**
* Removes output from Yoast SEO on the frontend for a specific post,page or custom post type.
*/
function remove_wpseo() {
if ( is_single ( 1 ) ) {
$front_end = YoastSEO()->classes->get( Yoast\WP\SEO\Integrations\Front_End_Integration::class );
remove_action( 'wpseo_head',[ $front_end,'present_head' ],-9999 );
}
}; ?>
更多信息@https://developer.yoast.com/customization/yoast-seo/disabling-yoast-seo/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。