Previous and Next Lesson Links Within a Category
Adds "Previous lesson" and "Next lesson" links at the end of posts in your course categories, in publishing order, so readers can work through a series.
Opens WPIDE on
Code
// Category slugs that hold lesson series.
$wpide_course_categories = array( 'course-1' );
add_filter( 'the_content', function ( $content ) use ( $wpide_course_categories ) {
if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() || ! has_category( $wpide_course_categories ) ) {
return $content;
}
$prev = get_adjacent_post( true, '', true, 'category' );
$next = get_adjacent_post( true, '', false, 'category' );
if ( ! $prev && ! $next ) {
return $content;
}
$nav = '<nav class="wpide-lesson-nav" aria-label="Lesson navigation" style="display:flex;flex-wrap:wrap;justify-content:space-between;gap:1em;margin-top:2em">';
$nav .= $prev ? '<a rel="prev" href="' . esc_url( get_permalink( $prev ) ) . '">← ' . esc_html( get_the_title( $prev ) ) . '</a>' : '<span></span>';
$nav .= $next ? '<a rel="next" href="' . esc_url( get_permalink( $next ) ) . '">' . esc_html( get_the_title( $next ) ) . ' →</a>' : '';
return $content . $nav . '</nav>';
} );
Notes
List the category slugs that are courses in $wpide_course_categories. Links stay inside the same category.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.