Previous/Next links within primary category only
-
I’m currently using the following code to limit previous/next links within the same category.
add_filter( 'next_post_link', 'my_adjacent_post_link', 10, 5 ); add_filter( 'previous_post_link', 'my_adjacent_post_link', 10, 5 ); function my_adjacent_post_link( $output, $format, $link, $post, $adjacent ) { $previous = 'previous' === $adjacent; if ( ! ( $previous && is_attachment() ) ) { $post = get_adjacent_post( true, '', $previous, 'category' ); } if ( ! $post ) { $output = ''; } else { $title = $post->post_title; if ( empty( $post->post_title ) ) { $title = $previous ? __( 'Previous Post' ) : __( 'Next Post' ); } $title = apply_filters( 'the_title', $title, $post->ID ); $date = mysql2date( get_option( 'date_format' ), $post->post_date ); $rel = $previous ? 'prev' : 'next'; $string = '<a href="' . get_permalink( $post ) . '" rel="' . $rel . '">'; $inlink = str_replace( '%title', $title, $link ); $inlink = str_replace( '%date', $date, $inlink ); $inlink = $string . $inlink . '</a>'; $output = str_replace( '%link', $inlink, $format ); } return $output; }
The problem is that if a post is in multiple categories, the adjacent post retrieved is a match for any of those categories.
I want to limit results to ONLY posts in the same PRIMARY category.
There must be a way to do this. So far, I’ve only been able to find posts about returning the primary category name. Can anyone help me?
Thanks in advance!
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
- The topic ‘Previous/Next links within primary category only’ is closed to new replies.