Navigate Between Terms in Custom Post Type Taxonomy

Sourced here, this snippet can be inserted within single.php and used to isolate the previous and next navigation links when working with Custom Post Types that have multiple Taxonomies and Terms to allow for more streamlined navigation:

// get_posts in same custom taxonomy

$postlist_args = array(
   'posts_per_page'  => -1,
   'orderby'         => 'menu_order title',
   'order'           => 'ASC',
   'post_type'       => 'your_custom_post_type',
   'your_custom_taxonomy' => 'your_custom_taxonomy_term'
); 

$postlist = get_posts( $postlist_args );



// get ids of posts retrieved from get_posts

$ids = array();

foreach ($postlist as $thepost) {

   $ids[] = $thepost->ID;

}



// get and echo previous and next post in the same taxonomy        

$thisindex = array_search($post->ID, $ids);
$previd = $ids[$thisindex-1];
$nextid = $ids[$thisindex+1];

if ( !empty($previd) ) {

   echo '<a rel="prev" href="' . get_permalink($previd). '">previous</a>';

}

if ( !empty($nextid) ) {

   echo '<a rel="next" href="' . get_permalink($nextid). '">next</a>';

}

Customized to find the term name automagically and use images in place of navigation text:

<?php 

$terms = get_the_terms( $post->ID, 'your_custom_taxonomy' );

foreach ($terms as $term) {}



// get_posts in same custom taxonomy
$postlist_args = array(
   'posts_per_page'  => -1,
   'orderby'         => 'menu_order title',
   'order'           => 'ASC',
   'post_type'       => 'your_custom_post_type',
   'your_custom_taxonomy' => $term->slug
); 

$postlist = get_posts( $postlist_args );



// get ids of posts retrieved from get_posts

$ids = array();

foreach ($postlist as $thepost) {

   $ids[] = $thepost->ID;

}



// get and echo previous and next post in the same taxonomy        

$thisindex = array_search($post->ID, $ids);

$previd = $ids[$thisindex-1];

$nextid = $ids[$thisindex+1];

if ( !empty($previd) ) { ?>

   <a rel="prev" href="<?php get_permalink($previd); ?>"><img src="<?php bloginfo('stylesheet_directory'); ?>/img/back.png" /></a>

<?php }

if ( !empty($nextid) ) { ?>

   <a rel="next" href="<?php get_permalink($nextid); ?>"><img src="<?php bloginfo('stylesheet_directory'); ?>/img/forward.png" /></a>

<?php } ?>

Leave a Reply

Posted in php
katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.