Breadcrumb JSON-LD Builder
Builds BreadcrumbList JSON-LD from ordered breadcrumb labels and protocol-relative site URLs.
Purpose
Builds BreadcrumbList JSON-LD from ordered breadcrumb labels and protocol-relative site URLs.
Snippet details
ContextSeoLevelAdvancedCopy-and-paste statusMarked safe after review.Categories
- Security
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Breadcrumb JSON-LD Builder.
*
* Purpose:
* Builds BreadcrumbList JSON-LD from ordered breadcrumb labels and protocol-relative site URLs.
*
* @param array $breadcrumbs Ordered breadcrumb rows with name and url.
* @return string JSON-LD script payload.
*/
function ogSnippetBreadcrumbJsonldBuilder(array $breadcrumbs): string {
$items = array();
$position = 1;
foreach ($breadcrumbs as $breadcrumb) {
$name = '';
if (isset($breadcrumb['name'])) {
$name = trim((string) $breadcrumb['name']);
}
$url = '';
if (isset($breadcrumb['url'])) {
$url = trim((string) $breadcrumb['url']);
if (strpos($url, '//') === 0) {
$url = 'https:'.$url;
}
}
if ($name === '' || $url === '') {
continue;
}
$items[] = array(
'@type' => 'ListItem',
'position' => $position,
'name' => $name,
'item' => $url
);
$position++;
}
$payload = array(
'@context' => 'https://schema.org',
'@type' => 'BreadcrumbList',
'itemListElement' => $items
);
return json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
}
$expanse_breadcrumbs = array(
array('name' => 'Rocinante', 'url' => '//example.com/rocinante'),
array('name' => 'Ops Deck', 'url' => '//example.com/rocinante/ops')
);
$jsonld = ogSnippetBreadcrumbJsonldBuilder($expanse_breadcrumbs);
echo substr($jsonld, 0, 32);