Words and code and rock and roll

Breadcrumbs on archive pages in WordPress

Published 2012-2-21

When I was editing a WordPress archive page the other day, I decided that I wanted to list the categories and sub categories together with the archive result (the title with link), but without the links to the specific category pages. Some of the links on the archive page would have just one category, and some would have more, depending on the post. This is on a page that uses  WordPress as a CMS, not just for blogging.

The solution I came up with, used the wp_get_object_terms function, that I earlier had used together with a custom taxonomy query.  The categories are stored in the term ‘category’. To make sure the categories and sub categories was displayed in the right order (parent before sub), the output had to be ordered ascending (as the parent categories on this specific page all has a lover ID than the sub categories). And I used : as a separator between the categories and post title.

All entries included title, link, last change date, and the excerpt. The code ended up something like this:

<?php while (have_posts()) : the_post(); ?>
 <div <?php post_class() ?>>
 <h2 id="post-<?php the_ID(); ?>">
 $args = array('orderby' => 'ID', 'order' => 'ASC', 'fields' => 'all');
 $category_terms = wp_get_object_terms($post->ID, 'category', $args);
 if(!is_wp_error( $category_terms )){
 foreach($category_terms as $term){
 echo $term->name.' : '; 
 <a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
 <p class="changed-archive">Last modified: <?php the_modified_date(); ?></p>
<div class="entry">
 <?php the_excerpt(); ?>
<?php endwhile; ?>

Which gave this output (in Norwegian, mind):

[caption id="attachment_475" align="aligncenter" width="431" caption="Archive page with breadcrumb trail"]Archive page with breadcrumb trail[/caption]

I’ve also ended up using this solution on my post pages as well, but then combined with links.