Breadcrumb Structured Data for Posts and Pages
Adds BreadcrumbList JSON-LD to posts (Home > Category > Post) and pages (Home > Parent > Page) so Google can show a breadcrumb trail instead of a raw URL.
Opens WPIDE on
Code
add_action( 'wp_head', function () {
if ( ! is_singular() || is_front_page() || defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'AIOSEO_VERSION' ) || defined( 'SEOPRESS_VERSION' ) || defined( 'THE_SEO_FRAMEWORK_VERSION' ) ) {
return;
}
$post = get_queried_object();
$trail = array( array( get_bloginfo( 'name' ), home_url( '/' ) ) );
if ( 'post' === $post->post_type ) {
$categories = get_the_category( $post->ID );
if ( $categories ) {
$ids = array_reverse( get_ancestors( $categories[0]->term_id, 'category', 'taxonomy' ) );
$ids[] = $categories[0]->term_id;
foreach ( $ids as $term_id ) {
$url = get_term_link( (int) $term_id, 'category' );
if ( ! is_wp_error( $url ) ) {
$trail[] = array( get_term( $term_id, 'category' )->name, $url );
}
}
}
} elseif ( is_post_type_hierarchical( $post->post_type ) ) {
foreach ( array_reverse( get_post_ancestors( $post ) ) as $ancestor ) {
$trail[] = array( get_the_title( $ancestor ), get_permalink( $ancestor ) );
}
}
$trail[] = array( get_the_title( $post ), get_permalink( $post ) );
$list = array();
foreach ( $trail as $index => $crumb ) {
$list[] = array(
'@type' => 'ListItem',
'position' => $index + 1,
'name' => wp_strip_all_tags( $crumb[0] ),
'item' => $crumb[1],
);
}
$data = array(
'@context' => 'https://schema.org',
'@type' => 'BreadcrumbList',
'itemListElement' => $list,
);
echo '<script type="application/ld+json">' . wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG ) . "</script>\n";
} );
Notes
Skipped automatically when Yoast SEO, Rank Math, AIOSEO, SEOPress or The SEO Framework is active.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.