I'm trying to implement a breadcrumbs scheme in wordpress without a plugin, on category and tag pages.
I turned the breadcrumb I used into a schema,it works but only problem is i can't set position value in schema.
To give an example, things go wrong in a sub-category.
This is the code i use;
function schema_breadcrumbs() {
$text['home'] = 'Home';
$text['category'] = '"name": "%1$s"';
$text['url'] = '"@id": "%s",';
$text['tag'] = '"name": "%1$s"';
$wrap_before = '<script type="application/ld+json">{"@context": "https://schema.org", "@type": "BreadcrumbList","itemListElement": [';
$wrap_after = '] } </script>';
$before = '{ "@type": "ListItem","position": 2,';
$after = '}';
$show_home_link = 1;
$show_current = 1;
global $post;
$home_url = home_url('/');
$link = '{ "@type": "ListItem",';
$link .= '"position": 1, "item": { "@id": "%1$s", "name": "%2$s" }';
$link .= '},';
$parent_id = ( $post ) ? $post->post_parent : '';
$home_link = sprintf( $link, $home_url, $text['home'], 1 );
$position = 0;
echo $wrap_before;
if ( $show_home_link ) {$position += 1; echo $home_link;}
if ( is_category() ) {
$parents = get_ancestors( get_query_var('cat'), 'category' );
foreach ( array_reverse( $parents ) as $cat ) {
$position += 1;
echo sprintf( $link, get_category_link( $cat ), get_cat_name( $cat ), $position ); }
if ( $show_current ) {
echo $before . sprintf( $text['url'], get_category_link( get_queried_object() ) ), sprintf( $text['category'], single_cat_title( '', false ) ) . $after;} }
elseif ( is_tag() ) {
if ( $show_current )
echo $before . sprintf( $text['url'], get_category_link( get_queried_object() ) ), sprintf( $text['tag'], single_tag_title( '', false ) ) . $after; }
echo $wrap_after;
}
output goes like this
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [{
"@type": "ListItem",
"position": 1,
"item": {
"@id": "http://www.example.com/",
"name": "Home"
}
}, {
"@type": "ListItem",
"position": 1,
"item": {
"@id": "http://www.example.com/category/",
"name": "Category"
}
}, {
"@type": "ListItem",
"position": 2,
"@id": "http://www.example.com/category/sub-category/",
"name": "Sub Category"
}]
}