Categories
Development Wordpress

How to create page breadcrumbs in WordPress

Someone at the WordPress StackExchange site was wondering how you could display a list of a page’s ancestors. Pretty much that is the idea of breadcrumbs, so I answered his question using the handy get_ancestors() function.

Below is the code of the function I created to solve the problem. I called it “print_page_parents,” but it might as well be called “page_breadcumbs” =)

Hope you find it useful!

<?php
/**
 * Print list of ancestors in breadcrum fashion, from lowest to highest hierarchy or viceversa.
 *
*/
function print_page_parents($reverse = false){
  global $post;

  //create array of pages (i.e. current, parent, grandparent)
  $page = array($post->ID);
  $page_ancestors = get_ancestors($post->ID, 'page');
  $pages = array_merge($page, $page_ancestors);

  if($reverse) {
    //reverse array (i.e. grandparent, parent, current)
    $pages = array_reverse($pages);
  }

  for($i=0; $i<count($pages); $i++) {
    $output.= get_the_title($pages[$i]);
    if($i != count($pages) - 1){
      $output.= " » ";
    }
  }
    echo $output;
}

//print lowest to highest
print_page_parents();

//print highest to lowest
print_page_parents($reverse = true);

?>

 

Categories
Development Uncategorized

WordPress: How to display posts within a page

We have all been there: for some reason, you really need to display a list of posts within a page in WordPress. And the list needs to be paginated, of course…

Fortunately, there is a way to do it. The WordPress Codex Page reference has a nice (though pretty much buried) example of a page template to get you started:

How to display posts within a page:
http://codex.wordpress.org/Pages#A_Page_of_Posts

As a great addition, it also has an example of a how to display custom post types within a page as well:

How to display a custom post type within a page:
http://codex.wordpress.org/Pages#Using_Custom_Post_Types

I found this definitely helpful, and hopefully you will too!

Happy coding!