Create json ld breadcrumbs dynamically

PHP-FPMNikolas1 min read

[av_one_full first min_height=” vertical_alignment=” space=” custom_margin=” margin=’0px’ row_boxshadow=” row_boxshadow_color=” row_boxshadow_width=’10’ link=” linktarget=” link_hover=” title_attr=” alt_attr=” padding=’0px’ highlight=” highlight_size=” border=” border_color=” radius=’0px’ column_boxshadow=” column_boxshadow_color=” column_boxshadow_width=’10’ background=’bg_color’ background_color=” background_gradient_color1=” background_gradient_color2=” background_gradient_direction=’vertical’ src=” background_position=’top left’ background_repeat=’no-repeat’ animation=” mobile_breaking=” mobile_display=” av_uid=’av-2wyn’]

[av_textblock size=” av-medium-font-size=” av-small-font-size=” av-mini-font-size=” font_color=” color=” id=” custom_class=” av_uid=’av-jzqtmgtk’ admin_preview_bg=”]
In this post you will learn how to generate json ld breadcrumbs for your php website.

<?php
function jsonbreadcrumbs($home = 'Home') {
$itemNumber = 1;
$jsonbreadcrumb .= '<script type="application/ld+json">';
$jsonbreadcrumb .= '{';
$jsonbreadcrumb .= '"@context": "http://schema.org",';
$jsonbreadcrumb .= '"@type": "BreadcrumbList",';
$root_domain = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/';
$jsonbreadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$jsonbreadcrumb .= '"itemListElement": [{';
$jsonbreadcrumb .= '"@type": "ListItem",';
$jsonbreadcrumb .= '"position":' .$itemNumber++.',';
$jsonbreadcrumb .= ""name": "{$home}",";
$jsonbreadcrumb .= ""item": "{$root_domain}"},";
foreach ($jsonbreadcrumbs as $crumb) {
  $link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
  $root_domain .=  $crumb . '/';
  $jsonbreadcrumb .= '{"@type": "ListItem",';
  $jsonbreadcrumb .= '"position":' . $itemNumber++ . ',';
  $jsonbreadcrumb .= ""name": "{$link}",";
  $jsonbreadcrumb .= ""item": "{$root_domain}"},";
  }
$jsonbreadcrumb = trim($jsonbreadcrumb,",");
$jsonbreadcrumb .= ']}</script>';
return $jsonbreadcrumb;
}
echo jsonbreadcrumbs();
?>

[/av_textblock]

[/av_one_full]