[英]WP SEO Yoast plugin breadcrumb and JSON-LD (BreadcrumbList) integration
我正在嘗試將yoast_breadcrumb API與JSON-LD集成。
根據SEO Yoast插件文檔,我有以下面包屑代碼:
<?php
yoast_breadcrumb();
?>
但是,我正在嘗試通過下面的JSON-LD代碼示例將JSON-LD模式與Yoast Breadcrumb API集成在一起,並且我在文檔中找不到任何地方可以實現此目的,該API會顯示BreadcrumbList的HTML格式,不是我想要的,我想要數組格式,以便能夠使用foreach loop構造JSON-LD。
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement":
[
{
"@type": "ListItem",
"position": 1,
"item":
{
"@id": "https://example.com/news/",
"name": "News"
}
},
{
"@type": "ListItem",
"position": 2,
"item":
{
"@id": "https://example.com/news/finance/",
"name": "Finance"
}
}
]
}
您可以過濾輸出並收集JSON。 但是,在下面提供的示例中,如果要在文檔的開頭部分輸出,則“收集”可能會很晚。 然后,您可以更早地調用面包屑函數,而無需回顯它並收集數據,刪除過濾器並呈現JSON。
/* echo breadcrumbs in template */
yoast_breadcrumb('<p id="breadcrumbs">','</p>');
/* collect breadcrumb whenever */
$breadcrumbs = yoast_breadcrumb('','',false);
這是過濾器功能:
add_filter('wpseo_breadcrumb_links', 'entex_add_crumb_schema', 10, 1);
function entex_add_crumb_schema($crumbs) {
if( ! is_array( $crumbs ) || $crumbs === array()){
return $crumbs;
}
$last = count($crumbs);
$listItems = [];
$j = 1;
foreach ( $crumbs as $i => $crumb ) {
$item = [];
$nr = ($i + 1);
if(isset($crumb['id'])){
$item = [
'@id' => get_permalink($crumb['id']),
'name' => strip_tags( get_the_title( $id ) )
];
}
if(isset($crumb['term'])){
$term = $crumb['term'];
$item = [
'@id' => get_term_link( $term ),
'name' => $term->name
];
}
if(isset($crumb['ptarchive'])){
$postType = get_post_type_object($crumb['ptarchive']);
$item = [
'@id' => get_post_type_archive_link($crumb['ptarchive']),
'name' => $postType->label
];
}
/* READ NOTE BELOW: */
if($nr == $last){
if(is_author() && !isset($crumb['url'])) $crumb['url'] = esc_url(get_author_posts_url(get_queried_object_id()));
}
/* The 'text' indicates the current (last) or start-path crumb (home)*/
if(isset($crumb['url'])) {
if($crumb['text'] !== '') {
$title = $crumb['text'];
} else {
$title = get_bloginfo('name');
}
$item = [
'@id' => $crumb['url'],
'name' => $title
];
}
$listItem = [
'@type' => 'ListItem',
'position' => $j,
'item' => $item
];
$listItems[] = $listItem;
$j++;
}
$schema = [
'@context' => 'http://schema.org',
'@type' => 'BreadcrumbList',
'itemListElement' => $listItems
];
$html = '<script type="application/ld+json">' . stripslashes(json_encode($schema, JSON_PRETTY_PRINT)) . '</script> ';
echo $html;
remove_filter('wpseo_breadcrumb_links', 'entex_add_crumb_schema', 10, 1);
return $crumbs;
}
(*)注意Yoast不會將URL填充到當前登錄頁面/歸檔登錄頁面。 您必須在函數中為作者檔案添加示例。 這取決於您是否要在模式中使用當前路徑,因此我將在每個用戶案例中進行修改。
(*)提示這是RAW示例。 對您填充的var進行一些檢查,以避免javascript范圍問題。 此外,僅當使用PRETTY參數時才需要最后一個反斜杠。
快樂的JSON
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.