Search code examples
wordpressschemabreadcrumbs

How to Generate Breadcrumb Schema Dynamically in Wordpress (all pages, child pages, custom post type and taxonomy)


<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [{
    "@type": "ListItem",
    "position": 1,
    "name": "Home",
    "item": "https://example.com/"
  },{
    "@type": "ListItem",
    "position": 2,
    "name": "<?php the_title(); ?>",
    "item": "<?php the_permalink(); ?>"
  }
  ]
}

I am using this code for dynamic Breadcrumb schema but it work only first level pages and default post , i need to work all custom post type and custom taxonomy. can you please help me?


Solution

  • try this script

    <script>
        var bread = {
            "@@context": "https://www.schema.org",
            "@@type": "BreadcrumbList",
            "itemListElement": []
        }
        var exist = false;
        $('.breadcrumb li').each(function (index) {
            var item = {}
            var href = $(this).find("a").attr('href');
            if (href) item["@@id"] = "@Repository.Settings["WebSiteAddress"]" + href // OR location.protocol+"//"+location.host+href;
            else item["@@id"] = "@Repository.Settings["WebSiteAddress"]" + window.location.pathname
            item["name"] = $.trim($(this).text());
    
            bread.itemListElement.push({
                "@@type": "ListItem",
                "position": index + 1,
                item
            })
            exist = true;
        });
        if(exist){
            var jsonStrb = JSON.stringify(bread);
       var s2 = document.createElement("script");
       s2.type = "application/ld+json";
       s2.id = "BreadcrumbJson";
       $("body").append(s2);
        $('#BreadcrumbJson').append(jsonStrb);
        }        </script>