wordpresspaginationnavigationcustom-post-typeshow

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 :-=

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.


Solution

  • 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.