Skip to content

Instantly share code, notes, and snippets.

@jnpkr
Created October 26, 2017 18:56
Show Gist options
  • Save jnpkr/a0b1f49a26c8a45914eb2826ea4e6a26 to your computer and use it in GitHub Desktop.
Save jnpkr/a0b1f49a26c8a45914eb2826ea4e6a26 to your computer and use it in GitHub Desktop.
Quick and dirty WordPress drop-in plugin to generate BreadcrumbList structured data for nested posts/pages
<?php
/*
Plugin Name: Parkwood JSON-LD Breadcrumbs
Plugin URI: http://www.parkwooddigital.com/
Description: Generate JSON-LD breadcrumbs structured data for Google on pages
Author: Jon Parker <[email protected]>
Version: 1.0
Author URI: http://www.parkwooddigital.com/
*/
function parkwood_json_ld_breadcrumbs() {
global $post;
$ancestors = get_post_ancestors( $post->ID );
if ( $ancestors ) {
$ancestors = array_reverse($ancestors);
$ancestors[] = $post->ID;
}
if ( $ancestors ) {
?>
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement":
[
<?php foreach($ancestors as $key => $id): ?>
{
"@type": "ListItem",
"position": <?php echo $key + 1; ?>,
"item":
{
"@id": "<?php echo get_permalink($id); ?>",
"name": "<?php echo esc_js( get_the_title($id) ); ?>"
}
}<?php echo ( $key + 1 < count($ancestors) ) ? ',' : '' ; ?>
<?php endforeach; ?>
]
}
</script>
<?php
} // end if
}
add_action( 'wp_head', 'parkwood_json_ld_breadcrumbs' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment