-
-
Save jdmgarcia/dbf864fd7cc50c1ebbebeae84bc7b186 to your computer and use it in GitHub Desktop.
Add schema to yoast seo breadcrumbs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add schema to yoast seo breadcrumb | |
*/ | |
add_filter('wpseo_breadcrumb_links', 'jj_add_crumb_schema', 10, 1); | |
function jj_add_crumb_schema($crumbs) { | |
if ( ! is_array( $crumbs ) || $crumbs === array() ) { | |
return $crumbs; | |
} | |
$listItems = []; | |
$j = 1; | |
foreach ( $crumbs as $i => $crumb ) { | |
$item = []; | |
if ( isset( $crumb['id'] ) ) { | |
$item = [ | |
'@id' => get_permalink($crumb['id']), | |
'name' => strip_tags( get_the_title( $id ) ) | |
]; | |
} | |
if ( isset( $crumb['term'] ) ) { | |
$term = $crumb['term']; | |
$item = [ | |
'@id' => get_term_link( $term ), | |
'name' => $term->name | |
]; | |
} | |
if ( isset( $crumb['ptarchive'] ) ) { | |
$postType = get_post_type_object($crumb['ptarchive']); | |
$item = [ | |
'@id' => get_post_type_archive_link($crumb['ptarchive']), | |
'name' => $postType->label | |
]; | |
} | |
if(isset($crumb['url'])) { | |
if($crumb['text'] !== '') { | |
$title = $crumb['text']; | |
} else { | |
$title = get_bloginfo('name'); | |
} | |
$item = [ | |
'@id' => $crumb['url'], | |
'name' => $title | |
]; | |
} | |
$listItem = [ | |
'@type' => 'ListItem', | |
'position' => $j, | |
'item' => $item | |
]; | |
$listItems[] = $listItem; | |
$j++; | |
} | |
$schema = [ | |
'@context' => 'http://schema.org', | |
'@type' => 'BreadcrumbList', | |
'itemListElement' => $listItems | |
]; | |
$html = '<script type="application/ld+json">' . json_encode($schema) . '</script> '; | |
echo $html; | |
return $crumbs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment