gpt4 book ai didi

php - 如何在数组中添加结构化数据模式

转载 作者:行者123 更新时间:2023-12-03 11:22:21 25 4
gpt4 key购买 nike

如何将结构化数据 mainEntity 添加为数组 @type 问题?

正如您从我的代码中看到的,我需要将主要实体作为一个数组,以便我可以将高级自定义字段转发器行传递到架构中以尝试构建 FAQ .

我试图传递到结构化数据中的字段是一个非常基本的 ACF 转发器,您可以在这里看到:

<section class="faq">
<div class="container max-width px-5">
<div class="row">
<div class="col-lg-6 features-title-block">
<h2 class="mpc-header"> <?php if ( get_field('faq_header') ) : ?>
<?php the_field('faq_header'); ?>
<?php endif; ?></h2>
<?php if ( get_field('faq_sub_text') ) : ?>
<div class="pb-5"><?php the_field('faq_sub_text'); ?></div>
<?php endif; ?>
</div>
<div class="col-lg-6">
<?php if ( have_rows('faq') ) : ?>
<div class="accordion" id="accordionExample">
<?php while( have_rows('faq') ) : the_row(); ?>
<div class="card">
<div class="card-header" id="heading<?php echo get_row_index(); ?>">
<h2 class="mb-0">
<button class="btn btn-link d-inline-flex" type="button" data-toggle="collapse"
data-target="#collapse<?php echo get_row_index(); ?>" aria-expanded="true"
aria-controls="collapse<?php echo get_row_index(); ?>">
<?php the_sub_field('question'); ?>
</button>
</h2>
</div>
<div id="collapse<?php echo get_row_index(); ?>" class="collapse"
aria-labelledby="heading<?php echo get_row_index(); ?>" data-parent="#accordionExample">
<div class="card-body">
<?php the_sub_field('answer'); ?>
</div>
</div>
</div>
<?php endwhile; ?>
<?php
$schema = array(
'@context' => "https://schema.org",
'@type' => "FAQPage",
'mainEntity' => array()
);
global $schema;
if ( have_rows('faq') ) {
while ( have_rows('faq') ) : the_row();
$questions = array(
'@type' => 'Question',
'name' => get_sub_field('question'),
'acceptedAnswer' => array(
'@type' => "Answer",
'text' => get_sub_field('answer')
)
);
array_push($schema['mainEntity'], $questions);
endwhile;
function generate_faq_schema ($schema) {
global $schema;
echo '<script type="application/ld+json">'. json_encode($schema) .'</script>';
}
add_action( 'wp_footer', 'generate_faq_schema', 100 );
}
?>
<?php endif; ?>
<!-- endif have_rows('faq'); -->
</div>
</div>
</div>
</div>
</section>

最佳答案

我不是 WordPress 的专业人士,但如果您尽可能避免使用全局变量,这对您的应用程序会有好处。试试下面的代码。

<?php
function generate_faq_schema () {
if ( have_rows('faq') ) {
$schema = [
'@context' => "https://schema.org",
'@type' => "FAQPage",
'mainEntity' => array()
];
while ( have_rows('faq') ) : the_row();
$questions = [
'@type' => 'Question',
'name' => get_sub_field('question'),
'acceptedAnswer' => [
'@type' => "Answer",
'text' => get_sub_field('answer')
]
];
array_push($schema['mainEntity'], $questions);
endwhile;
echo '<script type="application/ld+json">'. json_encode($schema) .'</script>';
}
}
add_action( 'wp_footer', 'generate_faq_schema', 100 );

?>

还要检查 的第四个参数add_action here .

关于php - 如何在数组中添加结构化数据模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59758775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com