Skip to content

Instantly share code, notes, and snippets.

@acodesmith
Last active August 14, 2017 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acodesmith/f6097839aeb8713c41073b851899a4b6 to your computer and use it in GitHub Desktop.
Save acodesmith/f6097839aeb8713c41073b851899a4b6 to your computer and use it in GitHub Desktop.
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