Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.