Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress Breadcrumbs Data and HTML
<?php
/**
* @return object
*/
function get_breadcrumb_home()
{
return (object) [
'post_title' => __( 'Home', 'uncg-bryan' ),
'permalink' => site_url()
];
}
<?php
/**
* @param \WP_Post $post
* @return string
*/
function get_breadcrumb_html( \WP_Post $post )
{
$breadcrumb_data = get_breadcrumb_data( $post );
$li = array_map(function ($item) {
if( empty( $item->permalink ) )
return "<li class='breadcrumb-item active'><span>$item->post_title</span></li>";
return "<li class='breadcrumb-item'><a href='$item->permalink'>$item->post_title</a></li>";
}, $breadcrumb_data);
return "<div class='breadcrumb-wrap'><ul class='breadcrumb'>" . implode("", $li) . "</ul></div>";
}
<?php
/**
* @param \WP_Post $post
* @return array
*/
function get_breadcrumb_data( \WP_Post $post )
{
$post_ancestors = array_reverse( get_post_ancestors( $post ) );
$posts = [ get_breadcrumb_home() ];
if( ! empty( $post_ancestors ) ) {
$query = new \WP_Query([
'post_type' => $post->post_type,
'post__in' => $post_ancestors,
'orderby' => 'post__in'
]);
if ( $query->have_posts() ) {
// The Loop
while ( $query->have_posts() ) {
$query->the_post();
$posts[] = (object) [
'post_title' => $query->post->post_title,
'permalink' => get_permalink( $query->post )
];
}
wp_reset_postdata();
}
}
$posts[] = (object) [
'post_title' => get_the_title()
];
return $posts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.