如何以编程方式将模式代码插入wordpress,使其自动适用于目标帖子类型



我有这个模式json代码,需要添加到WordPress中。我知道如何将其添加到个人帖子中,但我正在寻找一种情况,即我不需要在每个帖子中手动添加。我想插入代码,使其自动适用于我所针对的特定帖子类型,在本例中为Matches。我不知道该怎么办。我有一些自定义字段,我想用php在代码中插入这些字段,但我不确定这样做是否可行。请帮忙,谢谢。

<script type="application/ld+json">
{
"@context":"http://schema.org",
"@type":"SportsEvent",
"name": "Team A vs Team B",
"description": "Team A vs Team B for League Match",
"startDate": "2020-03-01",
"endDate": "2020-03-01",
"competitor": [
{
"@type": "SportsTeam",
"name": "Team A",
"image":"https://example.com/wp-content/uploads/2015/03/650.png"
},
{
"@type": "SportsTeam",
"name": "Team B",
"image":"https://example.com/wp-content/uploads/2015/03/680.png"
}
],
"location": {
"@type": "Place",
"address": "Stadium of Team A"
}
}
</script>

您可以将此函数添加到主题的functions.php文件中

function sports_event_schema() {
echo '
<script type="application/ld+json">
{
"@context":"http://schema.org",
"@type":"SportsEvent",
"name": "Team A vs Team B",
"description": "Team A vs Team B for League Match",
"startDate": "2020-03-01",
"endDate": "2020-03-01",
"competitor": [
{
"@type": "SportsTeam",
"name": "Team A",
"image":"https://example.com/wp-content/uploads/2015/03/650.png"
},
{
"@type": "SportsTeam",
"name": "Team B",
"image":"https://example.com/wp-content/uploads/2015/03/680.png"
}
],
"location": {
"@type": "Place",
"address": "Stadium of Team A"
}
}
</script>';
}
if ( 'Matches' == get_post_type() ) {
add_action('wp_footer', 'sports_event_schema');
}

另一种选择是直接在页眉或页脚中添加json,并仅添加if语句:

<?php if ( 'Matches' == get_post_type() ) : ?>
<script type="application/ld+json">
{
"@context":"http://schema.org",
"@type":"SportsEvent",
"name": "Team A vs Team B",
"description": "Team A vs Team B for League Match",
"startDate": "2020-03-01",
"endDate": "2020-03-01",
"competitor": [
{
"@type": "SportsTeam",
"name": "Team A",
"image":"https://example.com/wp-content/uploads/2015/03/650.png"
},
{
"@type": "SportsTeam",
"name": "Team B",
"image":"https://example.com/wp-content/uploads/2015/03/680.png"
}
],
"location": {
"@type": "Place",
"address": "Stadium of Team A"
}
}
</script>
<?php endif; ?>

相关内容

最新更新