Show next x number of posts depending on current post in WordPress

Glenn Glenn's Blog 0 Comments

In a previous post we looked at how to order and number WordPress posts sequentially but what if you want to show the next x number of posts based on the current post on say a custom post detail page. Here’s how you can do it:-

Show next x number of posts depending on Current Post


<ul>
    <?php
        global $post;
        $current_post = $post;
	$site_url = get_site_url();
        for($i = 1; $i <= 3; $i++):
        $post = get_previous_post();
        setup_postdata($post);
		// add your own if condition
		if(condition) {
        echo '<li>';
		echo '<a class="title" href="' . get_permalink() . '" title="'  . get_the_title() . '">'  . get_the_title() . '</a>';
		echo '<a class="link" href="' . get_permalink() . '" title="'  . get_the_title() . '"></a>';
        echo '</li>';
		}
		else
		{
		echo '<li>';
		echo '<a class="eg-title" href="'. $site_url .'/your-landing-page" title="">Show all</a>';
		echo '</li>';
		// only show once with break
		break;
		}
		endfor;
        $post = $current_post; 

    ?>
</ul>

What the code does is pull the current post/custom post type and then show a specified number of next posts. In our case it’s 3 so you can swap out ‘3’ above to specify the number of ‘next’ posts to show. if you get to the end of your posts then it will display a link back to the main listing page (you need to specify your own landing page / directory).

About the Author
Show next x number of posts depending on current post in WordPress 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced WordPress Web Developer, Front-end and Back-end Developer & New Media Specialist with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries built up over a number of years.

Leave a Reply

Your email address will not be published. Required fields are marked *