Add prev and next post with title and thumb in the same category

Marko Krstić
22 Jun 2020
// set current category
$categories = get_the_category();
$category = $categories[0];
$cat_ID = $category->cat_ID;    

// get next post link
$next_post = get_adjacent_post( true, '', false );
if( $next_post ) {
    echo '<a href="' . get_permalink( $next_post->ID ) . '">Next post</a>';
} else {
    $first = new WP_Query( array(
        'post_type' => 'project',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'order' => 'ASC',
        'cat' => $cat_ID
    ));

    $first->the_post();
    echo '<a href="' . get_permalink() . '">Next post</a>';
    wp_reset_query();
};

// show prev post link
$prev_post = get_adjacent_post( true, '', true );
if( $prev_post ) {
    echo '<a href="' . get_permalink( $prev_post->ID ) . '">Prev post</a>';
} else {
    $last = new WP_Query( array(
        'post_type' => 'project',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'order' => 'DESC',
        'cat' => $cat_ID
    ));

    $last->the_post();
    echo '<a href="' . get_permalink() . '">Prev post</a>';
    wp_reset_query();
};

This one is work in progress

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy