Resolved: Schema breadcrumbs on category and tag pages

Question:

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"
    }]
}

Answer:

In $link, you can just replace the 1 with %3$d.
You’ll need to modify the string construction to append $position to the static portion.
You need to alter the echo line where $before is used to be sprintf() style like the other position output. Replace the 2 with %d, then output like so:
echo sprintf( $before, $position );
The rest is simple to do, you can do it too

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com