[英]Remove comma after last object in the Schema array with PHP WordPress Loop
我有一個“產品”谷歌架構標記,其中包含“評論”的粘貼循環。 這是標記代碼的一部分:
"review": [
<?php
$args = array(
'post_type' => 'my_reviews',
'category_name' => 'my-product',
'paged' => $paged);
$loop = new WP_Query($args);
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post(); ?>
{
"@type": "Review",
"reviewRating": {
"@type": "Rating",
"ratingValue": "5"
},
"author": {
"@type": "Person",
"name": "<?php the_title(); ?>"
},
"reviewBody": "<?php echo get_the_content(); ?>"},
<?php
endwhile;
endif;
wp_reset_postdata();
?>],
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": "5",
"bestRating": "5",
"ratingCount": "<?php echo count_cat_post('My Product'); ?>"
},
一切正常,除了在最后一個}
之后,逗號仍然被困住。 結果是這樣的:
"review": [{
"@type": "Review",
"reviewRating": {
"@type": "Rating",
"ratingValue": "5"
},
"author": {
"@type": "Person",
"name": "John Doe"
},
"reviewBody": "Review 1 Content"
},
{
"@type": "Review",
"reviewRating": {
"@type": "Rating",
"ratingValue": "1"
},
"author": {
"@type": "Person",
"name": "Jane Doe"
},
"reviewBody": "Review 2 Content."
}, <-- this is the comma I need to remove
],
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": "88",
"bestRating": "100",
"ratingCount": "2"
},
我怎樣才能刪除它?
在 wordpress 循環中,您擁有用於index
的屬性current_post
和用於total number of posts
post_count
。 您可以使用條件($loop->current_post + 1 != $loop->post_count)
來比較它不是最后一篇文章,然后您可以打印逗號。
所以你的get_the_content
代碼應該是這樣的:
"reviewBody": "<?php echo get_the_content(); ?>"} <?php if ($loop->current_post + 1,= $loop->post_count) { echo ';'? } ?>
您不應該通過與循環連接來創建 JSON,而是在循環內將文本添加到數組中,然后使用implode(',',$yourArray)
將數組轉換為 JSON,最后一個逗號將不存在。
甚至更好的方法是創建嵌套的 arrays,並使用json_encode()
function 從嵌套數組中創建有效的 JSON。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.