Created
January 5, 2012 18:29
-
-
Save trepmal/1566525 to your computer and use it in GitHub Desktop.
WordPress: Breadcrumb Functions
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 | |
/* | |
Plugin Name: Breadcrumb Functions | |
Description: Functions for displaying breadcrumbs when working with hierarchical post types. Does nothing out-of-the-box, functions must be added to theme (directly or via hooks, your discretion). | |
Author: Kailey Lampert | |
Author URI: http://kaileylampert.com/ | |
*/ | |
/* | |
Basic: | |
echo get_breadcrumbs( $post ); | |
//returns: <p><a href='{post_url}'>{post_title}</a> > <a href='{post_url}'>{post_title}</a></p> | |
Advanced: | |
echo get_breadcrumbs( $post, array( 'before_all' => '<ol>', 'after_all' => '</ol>', 'before_each' => '<li>', 'after_each' => '</li>', 'separator' => '' ) ); | |
//returns: <ol><li><a href='{post_url}'>{post_title}</a></li><li><a href='{post_url}'>{post_title}</a></li></ol> | |
*/ | |
function get_breadcrumbs( $starting_page, $deco = array( 'before_all' => '<p>', 'after_all' => '</p>', 'before_each' => '', 'after_each' => '', 'separator' => ' > ' ) ) { | |
//get our "decorations" | |
extract( $deco ); | |
//reverse it so the highest (most-parent?) page is first | |
$ids = array_reverse( _get_breadcrumbs( $post ) ); | |
//if only one id, there are no parents. show nothing | |
if ( count( $ids ) <= 1 ) return ''; | |
//loop through each, create decorated links | |
$links = array(); | |
foreach ( $ids as $url => $title ) { | |
$links[] = "$before_each<a href='$url'>$title</a>$after_each"; | |
} | |
//return it all together | |
return $before_all . implode( $separator, $links ) . $after_all; | |
} | |
//recursive function for getting all parent, grandparent, etc. IDs | |
//not intended for direct use | |
function _get_breadcrumbs( $starting_page, $container = array() ) { | |
//make sure you're working with an object | |
$sp = ( ! is_object( $starting_page ) ) ? get_post( $starting_page ) : $starting_page; | |
//make sure to insert starting page only once | |
if ( ! in_array( get_permalink( $sp->ID ), $container ) ) | |
$container[ get_permalink( $sp->ID ) ] = get_the_title( $sp->ID ); | |
//if parent, recursion! | |
if ( $sp->post_parent > 0 ) { | |
$container[ get_permalink( $sp->post_parent ) ] = get_the_title( $sp->post_parent ); | |
$container = _get_breadcrumbs( $sp->post_parent, $container ); | |
} | |
return $container; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment