【发布时间】:2020-03-28 21:49:58
【问题描述】:
我只想删除最后一个循环中的逗号,因为如果最后一部分仍有逗号,脚本将不起作用。
这是我正在使用的代码:
<?php
$faqs = get_field('questions_&_answers');
if( $faqs ) :
?>
<script type="application/ld+json">
{
"@context":"https://schema.org",
"@type":"FAQPage",
"mainEntity":[
<?php
if( have_rows('questions_&_answers') ):
$comma = ',';
$i = 1;
while ( have_rows('questions_&_answers') ) : the_row();
?>
{"@type":"Question","name":"<?=get_sub_field('question', false, false)?>","acceptedAnswer":{"@type":"Answer","text":"<?=get_sub_field('answer', false, false)?>"}}<?=($i < $faqs) ? $comma : '';?>
<?php
$i++;
endwhile;
endif;
?>
]
}
<?php
endif;
?>
</script>
这就是结果
{
"@context":"https://schema.org",
"@type":"FAQPage",
"mainEntity":[
{"@type":"Question","name":"My Question 1","acceptedAnswer":{"@type":"Answer","text":"My Answer 1"}},
{"@type":"Question","name":"My Question 2","acceptedAnswer":{"@type":"Answer","text":"My Answer 2"}},
]
}
看到循环的最后一部分“我的问题2”末尾还有逗号,需要去掉
【问题讨论】:
标签: php wordpress while-loop schema advanced-custom-fields