我有一个"产品";谷歌模式标记(Google Schema Markup(;评论";。这是Markup代码的一部分:
"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_encode
是正确的方式,但他在评论中说他想要这样。但对于未来的观众来说,正确的方法应该是这样的:
// define reviews array
$reviewArr = [
'review' => [],
'aggregateRating' => []
];
// get and loop through posts
$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();
// new post review
$post_review = [
"@type" => "Review",
"reviewRating" => [
"@type" => "Rating",
"ratingValue" => "5"
],
"author" => [
"@type" => "Person",
"name" => "<?php the_title(); ?>"
],
"reviewBody" => get_the_content()
];
// insert the post review in reviews array
$reviewArr['review'][] = $post_review;
endwhile;
endif;
wp_reset_postdata();
// aggregate rating
$aggRating = [
"@type" => "AggregateRating",
"ratingValue" => "5",
"bestRating" => "5",
"ratingCount" => count_cat_post('My Product')
];
// insert in reviews array
$reviewArr['aggregateRating'] = $aggRating;
// here you get your json
$json = json_encode($reviewArr);
您不应该通过与循环串联来创建JSON,而是应该在循环中将文本添加到数组中,然后使用implode(',',$yourArray)
将数组转换为JSON,因为最后一个逗号不存在。
或者更好的方法是创建嵌套数组,并使用json_encode()
函数从嵌套数组中创建一个有效的JSON。