WordPress show next 3 x number adjacent custom posts from existing

On a single/detail Custom Post Page I would like to display a custom nav of li’s or divs in a sidebar that displays both title, excerpt and permalink for the next 3 posts within the custom post series. So if we are on custom post 3 then it would show 4, 5, 6 in the sidebar.

The closest I’ve found to this is :-=

Read More
global $post;
$current_post = $post; // remember the current post

for($i = 1; $i <= 3; $i++){
 $post = get_previous_post(); // this uses $post->ID
setup_postdata($post);

// do your stuff here       
the_title();

}

$post = $current_post; // restore

Problem is this only shows the first next post and I need to show 3.

Thanks
Glennyboy

Related posts

Leave a Reply

2 comments

  1. The problem with your code is that get_previous_post() gets the post previous to the current post, so your for loop just gets the same post 3 times.

    What you need to use is wp_get_recent_posts. You would use it inside the WordPress loop, using a secondary loop to make that query.

    Depending on where you’re adding the code, you might just be able to use wp_get_recent_posts():

    $args = array(
        'numberposts' => 3,
        'orderby' => 'post_date',
        'order' => 'DESC',
        'post_type' => 'post');
    
    $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
    
  2. Your code from above is very close. It looks like you’re just missing an endfor; and maybe a bit of html. Try the blow code:

    <ul>
        <?php
            global $post;
            $current_post = $post;
    
            for($i = 1; $i <= 3; $i++):
            $post = get_previous_post();
            setup_postdata($post);
    
            echo '<li>';
            echo '<h3>' . get_the_title() . '</h3>';
            the_excerpt();
            echo get_post_meta($post->ID, 'your_metafield_name', true);
            echo '</li>';
    
            endfor;
            $post = $current_post; 
    
        ?>
    </ul>
    

    When using the_excerpt() it should include a “read more” link already to the post, so you won’t need to use the_permalink() function. If you don’t have 3 or more previous posts, it will only show how many previous posts there are. I tested this in the single.php template file, but it should work in a custom post type single template file if you are using a custom one. Let me know if you have any questions.