previous / next post with thumbnail

You need to send a custom query to get a list of posts. In this example we use a custom post type “project” and a custom taxonomy “sphere” and we get 1 next project in current sphere. In your use case you can increase posts_per_page to 4.

<?php 
//remember the id and menu_order from current post 
$id=get_the_ID(); 
global $haet_post_order; 
$haet_post_order=$post->menu_order;

//There is only one sphere per project in this example
$custom_terms = get_the_terms($id, 'sphere');
foreach ($custom_terms AS $term) {
    $sphere=$term->slug;
}

function haet_filter_next_post( $where="" ) {
    global $haet_post_order;
    $where .= ' AND menu_order>'.$haet_post_order;
    return $where;
}

add_filter( 'posts_where', 'haet_filter_next_post' );
$loop = new WP_Query( array( 'post_type' => 'project', 'posts_per_page' => 1,'orderby' => 'menu_order','order' => 'ASC','sphere'=>$sphere ) );
remove_filter( 'posts_where', 'haet_filter_next_post' );

//if there is no next post use the first one
if( !$loop->have_posts() ){
    $loop = new WP_Query( array( 'post_type' => 'project', 'posts_per_page' => 1,'orderby' => 'menu_order','order' => 'ASC','sphere'=>$sphere ) );
}

while ( $loop->have_posts() ) : $loop->the_post();
// place you code here
?>

<?php  endwhile;  ?>

Inside the while loop you can get the thumbnail with get_the_post_thumbnail(). You can find a few more lines of description in this blog post

Leave a Comment