Working on a client project in WordPress recently, I came across something I’d not thought of before…

Category based Previous and Next links on Custom Post Types.

I’d heard of category based links for standard blog post but I’d never actually seen it used. After a bit of Googling and looking back through previous projects I managed to find a solution.

The Use Case

  1. I have a custom post type called “Products”
  2. I have a custom taxonomy called “Product Categories”
  3. I have a bunch of products that I want to link to via product category
  4. Whilst in this individual product page I want to find out my current custom post type category and display previous and next links to allow me to navigate but only within my current product category

The Code

Here is the code I used to grab the current category and then get the posts based on that category…

<?php

// Get terms for post
$terms = get_the_terms( $post->ID , 'productcat' );
// Loop over each item since it's an array
if ( $terms != null ){
foreach( $terms as $term ) {
// Print the name method from $term which is an OBJECT
$termSlug = $term->slug;
// Get rid of the other data stored in the object, since it's not needed
unset($term);
} } ?>

<?php

$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

echo $term->slug; // will show the slug

// get_posts in same custom taxonomy
$postlist_args = array(
'posts_per_page' => -1,
'orderby' => 'menu_order title',
'order' => 'ASC',
'post_type' => 'product', // this can be your post type
'productcat' => $termSlug // get slug of product category from above - change productcat for your taxonomy 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];

?>

Then the following to display the above…

<?php

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>';
}

?>