我正在使用高级自定义字段插件以json ld格式生成模式数据。我正在为面包屑使用转发器,它工作得很好,但是为了获得有效的标记,我需要从最后一个转发器/面包屑项目中删除逗号。这是我的代码:
<?php if( have_rows(\'breadcrumb\') ): ?>
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
<?php while( have_rows(\'breadcrumb\') ): the_row();
// vars
$position = get_sub_field(\'position\');
$name = get_sub_field(\'name\');
$url = get_sub_field(\'url\');
?>
{
"@type": "ListItem",
"position": <?php echo $position; ?>,
"item": {
"@id": "<?php echo $url; ?>",
"name": "<?php echo $name; ?>"
}
}, // <-- This comma needs to go on last repeater item
<?php endwhile; ?>
]}
</script>
<?php endif; ?>
如果只有两个面包屑项目(减去最后一个项目上的逗号),则结果应为:
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{
"@type": "ListItem",
"position": 1,
"item": {
"@id": "http://example.com/",
"name": "Movies"
}
}, // <-- Comma because there\'s another list item to follow this one
{
"@type": "ListItem",
"position": 2,
"item": {
"@id": "http://example.com/avatar",
"name": "Avatar"
}
} // <-- No comma as this is the last list item
]
}
</script>
最合适的回答,由SO网友:David 整理而成
混合不同语言的代码不是一种好的做法。此外,无需构建JSON格式作为模板。您可以构建数据结构,然后使用json_encode()
:
<?php
if ( have_rows( \'breadcrumb\' ) ) {
$json_data = [
"@context" => "http://schema.org",
"@type" => "BreadcrumbList",
"itemListElement" => []
];
while ( have_rows( \'breadcrumb\' ) ) {
the_row();
// vars
$position = get_sub_field( \'position\' );
$name = get_sub_field( \'name\' );
$url = get_sub_field( \'url\' );
$json_data[ \'itemListElement\' ][] = [
"@type" => "ListItem",
"position" => $position,
"item" => [
"@id" => $url,
"name" => $name
]
];
}
$json_string = json_encode( $json_data );
$html_script = <<<HTML
<script type="application/json">{$json_string}</script>
HTML;
echo $html_script;
}
我假设此代码位于某种模板文件中,因为您可以直接打印结果。您应该考虑将业务逻辑(构建数据结构)与数据的表示/格式分离,因为这使代码更具可读性和可维护性。