WordPress show next 3 x number adjacent custom posts from existing

questions :

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

// do your stuff here       


$post = $current_post; // restore

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





Answer :

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:

        global $post;
        $current_post = $post;

        for($i = 1; $i <= 3; $i++):
        $post = get_previous_post();

        echo '<li>';
        echo '<h3>' . get_the_title() . '</h3>';
        echo get_post_meta($post->ID, 'your_metafield_name', true);
        echo '</li>';

        $post = $current_post; 


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.





Facebook Comments

Website Comments

  1. http://theguardian.com

    Eνeryone laսghed attempting to imagine what sort of celebration Mary and Joseph gave for Jesus when He wɑs
    six. Larry questioned, ?I bet he favored
    the identical type of toys we like.

Post a comment