I need navigation to two previous and two next posts, inside same category.

I made it working great for one previous and one next post inside same category. This is what I have now.

Previous post:

$prev_post = get_previous_post(TRUE);
$prev_post_thumb_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($prev_post->ID), 'thumbnail');
if (!empty( $prev_post )): ?>

<a href="<?php echo get_permalink( $prev_post->ID ); ?>"<img src="<?php echo $prev_post_thumb_image_url[0]; ?>"></a>

<?php endif; ?>

Next post:

$next_post = get_next_post(TRUE);
$next_post_thumb_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($next_post->ID), 'thumbnail');
if (!empty( $next_post )): ?>

<a href="<?php echo get_permalink( $next_post->ID ); ?>"><img src="<?php echo $next_post_thumb_image_url[0]; ?>"></a>

<?php endif; ?>

What I need is to check if there is two previous posts and to display than two previous thumbs and also check if there is next two posts and to display them if they exist. Of course it would be nice to display one previous/next post thumbs if there is no two previous posts. Even better to display next 4 posts on first and previous 4 posts on last page.

  • I just saw that my question is down voted. Why, what is wrong with this question? – Advanced SEO Aug 3 '14 at 7:59

From this answer:

Let's say you want to fetch the ID of the immediately previous post based on the current post's ID. This is what you'd do:

get_previous_post_id( $post_id ) {
    // Get a global post reference since get_adjacent_post() references it
    glob al $post;

    // Store the existing post object for later so we don't lose it
    $oldGlobal = $post;

    // Get the post object for the specified post and place it in the global variable
    $post = get_post( $post_id );

    // Get the post object for the previous post
    $previous_post = get_previous_post();

    // Reset our global object
    $post = $oldGlobal;

    if ( '' == $previous_post ) 
        return 0;

    return $previous_post->ID; 

You can do a similar thing to fetch the next post's ID ... and you can do this recursively if you need to get the previous previous post:

$two_posts_ago = get_previous_post_id( get_previous_post_id( $post->ID ) );
  • Will that give me previous / next posts in same category? Also could you please combine it will my code in question, I am not sure I will be able to manage it myself. So, I need to show previous 2, previous 1, current post, next 1 and next 2 post's thumbnails, in exact same category. Thank you. – Advanced SEO Aug 3 '14 at 7:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.